java中使用aes算法加解密示例
java中使用aes算法加解密示例在 Java 中使用 AES 算法进行加密和解密,可以使用 Java Cryptography Architecture (JCA) 提供的javax.crypto包。以下是一个示例代码,展示如何使用 AES 算法进行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
private static final String AES_ALGORITHM = "AES";
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_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 key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_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);
}
public static void main(String[] args) {
try {
String plainText = "Hello, World!";
String key = "MySecretKey123456";
String encryptedText = encrypt(plainText, key);
System.out.println("Encrypted Text: " + encryptedText);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted Text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}在上述代码中,我们使用javax.crypto包提供的Cipher类来执行 AES 加密和解密操作。 encrypt方法接受明文和密钥作为参数,使用 AES 算法对明文进行加密,并返回加密后的 Base64 编码字符串。 decrypt方法接受加密后的字符串和密钥作为参数,使用 AES 算法对密文进行解密,并返回解密后的明文。在main方法中,我们使用示例的明文和密钥进行加密和解密,并打印结果。请注意,在实际应用中,密钥的安全性和管理是非常重要的。确保使用足够强度的密钥,并采取适当的措施来保护密钥的安全性。
页:
[1]