简介:
AES加密算法(Advanced Encryption Standard)是一种对称加密算法,也称为高级加密标准。它是由美国国家标准与技术研究院(NIST)于2001年发布,作为DES加密算法的替代方案。AES加密算法使用128位、192位或256位密钥对数据进行加密和解密,具有高强度、高速度和易于实现等优点
特点:
- 安全性高: AES加密算法是一种安全性较高的加密算法,能够有效抵御暴力破解和其他攻击。
- 加密速度快: AES加密算法的加密速度相对较快,尤其是对于128位密钥长度的加密,可以在硬件上实现高速加密。
- 硬件实现方便: 由于AES加密算法采用了固定的算法结构,因此可以在硬件上实现高效加密。 兼容性好 AES加密算法已经被广泛应用,许多软件和硬件设备都支持该算法。
- 可扩展性强: AES加密算法的密钥长度可选128位、192位和256位,可以根据安全需求选择密钥长度。
- 开放性好: AES加密算法是一种公开的加密算法,任何人都可以使用和实现。
1. 实现工具类
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
// 将密码字符串转换为AES密钥
public static SecretKey generateAESKeyFromPassword(String password) {
byte[] key = password.getBytes(StandardCharsets.UTF_8);
return new SecretKeySpec(key, ALGORITHM);
}
// AES加密
public static String encrypt(String plaintext, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException("AES加密异常");
}
}
// AES解密
public static String decrypt(String encryptedText, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new RuntimeException("AES解密异常");
}
}
}
2. 测试Demo实例
public static void main(String[] args) {
// 将密码字符串转换为AES密钥
String password = "2D9EFAA464C24507BD62948FFED6BF5A";// 格式为16位的倍数
SecretKey secretKey = generateAESKeyFromPassword(password);
// 要加密的数据
String originalData = "Hello!AES";
// 使用公钥加密数据,并转换为Base64编码的字符串
String encryptedData = encrypt(originalData, secretKey);
// 使用私钥解密Base64编码的数据
String decryptedData = decrypt(encryptedData, secretKey);
System.out.println("Original data: " + originalData);
System.out.println("Encrypted data: " + encryptedData);
System.out.println("Decrypted data: " + decryptedData);
}