简介
AES(Advanced Encryption Standard)高级加密算法,它具有算法稳固,快速,简单等特点,成为2006之后最流行的加密算法之一。以下是它的特点:
(1)稳固:抵抗所有已知的攻击。
(2)快速:在多个平台上速度快,编码紧凑。
(3)简单:设计简单。
算法要求
(1)分组长度必须固定为 128 bit (即 16 bytes)
(2)密钥长度可以是128 bit、192 bit、256 bit 中的任意一个(如果数据块及密钥长度不足时,会补齐)
算法
private byte[] encryptWithAES(String plaintext, String key) throws
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
BadPaddingException,
IllegalBlockSizeException {
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(secureRandom);
SecretKey secretKey = keyGenerator.generateKey(); // 默认生成密钥长度为 16 bytes,即 128 bit
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // 加密
// cipher.init(Cipher.DECRYPT_MODE, secretKey); // 解密
return cipher.doFinal(plaintext.getBytes());
}