AES Cipher in Java
How to implementing AES cipher in JAVA and main problems you may find in this challenge.
When I started, I tried to do a parallel between my 3Des implementation and AES, so I discovered the first difference:
I tried to generate a SecretKey from a pass-phrase for AES in the following way,
However when I tested, it threw an exception "AES SecretKeyFactory not available".
So the solution was made some small change:
Then, you can use the key to encrypt/decrypt, for instance, the encryption code is as follows,
// Initialize the cipher
When I started, I tried to do a parallel between my 3Des implementation and AES, so I discovered the first difference:
I tried to generate a SecretKey from a pass-phrase for AES in the following way,
KeySpec aesSpec = new KeySpec(key.getBytes(), "AES");
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES");
SecretKey secretKey = keyFactory.generateSecret(aesSpec);
This is the very similar how I do with 3Des:
KeySpec TDesSpec = new DESKeySpec(key.getBytes());
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
SecretKey secretKey = keyFactory.generateSecret(aesSpec);
So the solution was made some small change:
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
There are two hints here:
- The key needs be multiples of 16;
- AES works with those keys sizes: 128, 192 and 256 bits.
Then, you can use the key to encrypt/decrypt, for instance, the encryption code is as follows,
// Initialize the cipher
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
// Define the mode [Cipher.ENCRYPT_MODE|Cipher.DECRYPT_MODE]
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
cryptogram = cipher.doFinal(data);
Comentários
Postar um comentário