I would like to utilize AES to do text encryption and decryption, how to generate key?
How-To
Here has sample code to generate key:
package test.albert.security; import java.security.NoSuchAlgorithmException; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import lombok.extern.slf4j.Slf4j; @Slf4j public class AESKeyGenerator { public static void main(String[] args) throws NoSuchAlgorithmException { AESKeyGenerator keyGen = new AESKeyGenerator(); log.info(keyGen.generateKey()); } public String generateKey() throws NoSuchAlgorithmException { String key = ""; try { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); key = toHex(secretKey.getEncoded()); } catch (NoSuchAlgorithmException e) { throw e; } return key; } private String toHex(final byte[] data) { final StringBuilder sb = new StringBuilder(data.length * 2); for (final byte b : data) { sb.append(String.format("%02X", b)); } return sb.toString(); } }
Here has sample code to do encrypt and decrypt:
package test.albert.security; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import lombok.extern.slf4j.Slf4j; @Slf4j public class AESUtils { private final static String SECURED_KEY = "A8167A5A6CF9783099B9FF34588C52B9"; public static String encrypt(String inputText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec secretKey = new SecretKeySpec(SECURED_KEY.getBytes(), "AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); String encryptedString = Base64.encodeBase64String(cipher.doFinal(inputText.getBytes())); return encryptedString; } public static String decrypt(String encryptedText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); SecretKeySpec secretKey = new SecretKeySpec(SECURED_KEY.getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(encryptedText.getBytes()))); return decryptedString; } public static void main(String[] args) throws Exception { String plainText = "test123abc"; String encryptedText = AESUtils.encrypt(plainText); String decryptedText = AESUtils.decrypt(encryptedText); log.info(encryptedText); log.info(decryptedText); } }
Remember to add commons-codec to your dependency in pom.xml
<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.11</version> </dependency>