在Java中,可以使用javax.crypto
包中的類和方法來實現AES加密。以下是一個簡單的AES加密和解密示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AesEncryptionExample {
public static void main(String[] args) throws Exception {
String originalText = "Hello, World!";
String encryptedText = encrypt(originalText, "AES");
String decryptedText = decrypt(encryptedText, "AES");
System.out.println("Original Text: " + originalText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
}
public static String encrypt(String plainText, String algorithm) throws Exception {
SecretKey secretKey = generateSecretKey(algorithm);
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);
}
public static String decrypt(String encryptedText, String algorithm) throws Exception {
SecretKey secretKey = generateSecretKey(algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static SecretKey generateSecretKey(String algorithm) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
keyGenerator.init(128); // 128-bit key size
return keyGenerator.generateKey();
}
}
這個示例中,我們首先使用KeyGenerator
生成一個AES密鑰,然后使用Cipher
類進行加密和解密操作。注意,我們需要對原始文本和加密后的文本進行Base64編碼,以便在輸出時更容易查看。
在實際應用中,你可能需要將密鑰存儲在一個安全的地方,而不是每次都生成一個新的密鑰。你可以使用SecretKeySpec
類來加載一個已存儲的密鑰。