Reading:
AES Encryption in Java

AES Encryption in Java

Metamug
AES Encryption in Java

AES Encryption in Java

AES requires following libraries

import java.security.MessageDigest;
import java.util.Arrays;
import java.nio.ByteBuffer;
import org.apache.commons.codec.binary.Base32;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

Here we are going to use Base32 instead of Base64 for encoding and decoding the encrypted data.

Encrypt


int input =  73102719;
String ALGO = "AES/ECB/PKCS5Padding"
//byte[] data =  ByteBuffer.allocate(4).putInt(_$licenseNo as Integer).array();
byte[] data =  ByteBuffer.allocate(4).putInt(input).array(); 
//generate the secretKey for encryption
String secret = "SOME_SECRET_VALUE"; 
byte[] key = secret.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16); 
secretKey = new SecretKeySpec(key, "AES");

Cipher cipher = Cipher.getInstance(ALGO);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
Base32 base32 = new Base32();
//Base64.getEncoder().encodeToString(cipher.doFinal(data));
String licenseKey = base32.encodeAsString(cipher.doFinal(data));

Decrypt

For decryption, we need to create another Cypher object, using above cipher variable won't work.

cipher2 = Cipher.getInstance(ALGO);
cipher2.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decoded = base32.decode(licenseKey)
int input =  ByteBuffer.wrap(cipher2.doFinal(decoded)).getInt()

If we don't used UTF-8 we will get the following error.

input length must be multiple of 16 when decrypting with padded cipher


Icon For Arrow-up
Comments

Post a comment