在Java中,对称加密算法是一类常用的加密技术,它们使用相同的密钥进行加密和解密操作。以下是AES、DES、3DES和RC4四种对称加密算法的介绍及Java示例。
1. AES(Advanced Encryption Standard)
简介:
AES,全称为高级加密标准,是美国联邦政府采用的一种区块加密标准。它采用分组加密的方式,每个数据块进行独立加密。AES提供了三种密钥长度:128位、192位和256位,密钥长度越高,安全性越强。AES算法被广泛应用于保护电子数据的机密性,如金融交易、网络通信等。
Java示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] originalBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(originalBytes);
return new String(decryptedBytes);
}
// 示例用法
public static void main(String[] args) throws Exception {
String key = "1234567890123456"; // AES密钥长度应为16(128位)、24(192位)或32(256位)字节
String plainText = "Hello, World!";
String encryptedText = encrypt(plainText, key);
String decryptedText = decrypt(encryptedText, key);
System.out.