Java AES128_ECB_PKCS5Padding
Java AES128_ECB_PKCS5Padding
資料來源: https://juejin.cn/post/7026635907742564365
package com.qzd.hit.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Demo {
/*** main
* @author qizai
* data: params
* encStr: Here, the length of the key must be a multiple of 16
*/
public static void main(String[] args) throws Exception {
// Encrypt Data
String key = "ROcb6JybnKILLOlO"; // Secret Key length must be (16 24 32)
String data = "[\"123456789\"]"; // Content to be encrypted
String encStr = encrypt(data, key); // Content to be decrypted
System.out.println(encStr); //Encrypted data: w6oijM0xddQrItnH3UybLQ==
// Decrypt Data
String decStr = decrypt(encStr, key);
System.out.println(decStr); //Decrypted data: ["123456789"]
}
public static String encrypt(String content, String password) {
if (StringUtils.isEmpty(content) || StringUtils.isEmpty(password)) {
System.out.println("AES encryption params is null");
return null;
}
try {
// Create cipher
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
byte[] byteContent = content.getBytes("UTF-8");
// Initialize as cryptographic cipher
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));
byte[] encryptByte = cipher.doFinal(byteContent);
return org.apache.commons.codec.binary.Base64.encodeBase64String(encryptByte);
} catch (Exception e) {
System.out.println("AES encryption operation has exception,content:{},password:{}", content, password, e);
}
return null;
}
public static String decrypt(String encryptContent, String password) throws Exception {
if (StringUtils.isEmpty(encryptContent) || StringUtils.isEmpty(password)) {
System.out.println("AES The request parameter is null");
return null;
}
Cipher cipher = null;
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
// Set to decryption mode
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
// Perform decryption operation
byte[] result = cipher.doFinal(org.apache.commons.codec.binary.Base64.decodeBase64(encryptContent));
return new String(result, "UTF-8");
}
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
// Generates the generator for the specified algorithm key
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
keyGenerator.init(128, random);
// Grnerate Key
SecretKey secretKey = keyGenerator.generateKey();
// Key converted to AES
return new SecretKeySpec(secretKey.getEncoded(), "AES");
}
}