AES+base64
时间: 2023-12-25 16:29:58 浏览: 34
AES+base64是一种常见的加密和编码组合。AES是一种对称加密算法,用于加密和解密数据。base64是一种编码方式,用于将二进制数据转换为可打印字符。
下面是一个使用AES和base64的示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESBase64Example {
private static final String AES_ALGORITHM = "AES";
private static final String ENCODING = "UTF-8";
public static String encrypt(String plainText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(ENCODING), AES_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(ENCODING));
return Base64.getEncoder().encodeToString(encryptedBytes); }
public static String decrypt(String encryptedText, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(ENCODING), 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, ENCODING);
}
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
String key = "ThisIsASecretKey";
String encryptedText = encrypt(plainText, key);
System.out.println("Encrypted text: " + encryptedText);
String decryptedText = decrypt(encryptedText, key);
System.out.println("Decrypted text: " + decryptedText);
}
}
```