I've been struggling with encryption for a while now, and I'm about to complete the process, however, I'm now encountering some issues with the IV. Here's my code:
IV generation
public static byte[] createIV(int size) {
byte[] iv = new byte[size];
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
return iv;
}
AES-256 cipher creation (key)
public static Map<String, byte[]> cipherAES() throws NoSuchAlgorithmException {
Map<String, byte[]> aes = new HashMap<String, byte[]>();
aes.put("IV", ConversionUtil.toHex(createIV(16), 16).getBytes());
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
Key encryptionKey = keyGen.generateKey();
aes.put("key", encryptionKey.getEncoded());
return aes;
}
toHex method
public static String toHex(byte[] data, int length) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i != length; i++) {
int v = data[i] & 0xff;
buf.append(DIGITS.charAt(v >> 4));
buf.append(DIGITS.charAt(v & 0xf));
}
return buf.toString();
}
Cipher initialization
SecretKey key = new SecretKeySpec(map.get("key"), 0, map.get("key").length, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(map.get("IV"), 0, 16));
If I provide an IV of 16 bytes with this format to the cipher:
8E12399C07726F5A8E12399C07726F5A
When I call the getIV method on the Cipher, I get this:
8E12399C07726F5A
which is exactly half the bytes I provided for the IV. This is currently causing several issues, since the server can decrypt the second part of the message but not the first one.
I'm using JCE libraries only:
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
Can anyone shed some light on this? Let me know if you need further details.