在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()
方法中演示了整個加密和解密的過程。