在Java中,可以使用javax.crypto
包中的Cipher
类来实现AES加密算法。以下是一个简单的示例代码来演示如何使用AES加密算法对字符串进行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESEncryption {
public static SecretKey generateAESKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();
}
public static String encrypt(String data, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {
SecretKey key = generateAESKey();
String data = "Hello, AES!";
String encryptedData = encrypt(data, key);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = decrypt(encryptedData, key);
System.out.println("Decrypted data: " + decryptedData);
}
}
在上面的示例中,我们首先使用generateAESKey()
方法生成一个AES密钥,然后使用encrypt()
方法对字符串进行加密,最后使用decrypt()
方法将加密后的字符串解密。最后,我们在main()
方法中演示了整个加密和解密的过程。