Reputation: 443
I have tried to encrypt some plaintext, which is in bytes, with a key, which is in bytes. However, the output I am getting is not what I am expecting.
public class AES {
public static byte[] encrypt(byte[] plainText, byte[] key) {
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] cipherText = cipher.doFinal(plainText);
return cipherText;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String byteToHex(byte[] hash) {
StringBuilder sb = new StringBuilder(hash.length * 2);
for (byte b : hash) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static void main(String args[]) {
byte plaintext[] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x58,0x63,(byte)0xaa,(byte)0xbb,(byte)0xcc,(byte)0xdd,(byte)0xee,(byte)0xff};
byte key[] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
byte[] encrypted = encrypt(plaintext, key);
System.out.println("Encrypted String : " + byteToHex(encrypted));
}
}
The output I am getting is: 814064943fe05668da1f3d2269a4ee22954f64f2e4e86e9eee82d20216684899
while I am expecting 69c4e0d86a7b0430d8cdb78070b4c55a
. I am using the plaintext and key from here
Upvotes: 1
Views: 835
Reputation: 78975
There are two things incorrect in your code.
You use PKCS5 padding while the original example doesn't use any padding.
You incorrectly copied the plain text.
So:
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
...
byte plaintext[] = { 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, (byte) 0x88,
(byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, (byte) 0xdd, (byte) 0xee, (byte) 0xff };
Result:
Encrypted String : 69c4e0d86a7b0430d8cdb78070b4c55a
Upvotes: 2