import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
public class AESUtil {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
public static byte[] getSecretKey(String randomKey) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
if (StringUtils.isBlank(randomKey)) {
keyGenerator.init(128);
} else {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(randomKey.getBytes());
keyGenerator.init(128, random);
}
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
public static byte[] encrypt(byte[] data, Key key) throws Exception {
return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
return encrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
public static byte[] encrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception {
Key k = toKey(key);
return encrypt(data, k, cipherAlgorithm);
}
public static byte[] encrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
public static byte[] decrypt(byte[] data, Key key) throws Exception {
return decrypt(data, key, DEFAULT_CIPHER_ALGORITHM);
}
public static byte[] decrypt(byte[] data, byte[] key, String cipherAlgorithm) throws Exception {
Key k = toKey(key);
return decrypt(data, k, cipherAlgorithm);
}
public static byte[] decrypt(byte[] data, Key key, String cipherAlgorithm) throws Exception {
Cipher cipher = Cipher.getInstance(cipherAlgorithm);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(data);
}
public static Key toKey(byte[] secretKey) {
return new SecretKeySpec(secretKey, KEY_ALGORITHM);
}
public static void main(String[] args) throws Exception {
String password = "123456";
byte[] secretKey = getSecretKey(password);
Key key = toKey(secretKey);
String data = "AES 对称加密算法";
System.out.println("明文 :" + data);
byte[] encryptData = encrypt(data.getBytes(), key);
String encryptDataHex = Hex.encodeHexString(encryptData);
System.out.println("加密 : " + encryptDataHex);
byte[] decryptData = decrypt(Hex.decodeHex(encryptDataHex.toCharArray()), key);
System.out.println("解密 : " + new String(decryptData));
}
}