写一个Java程序使用aes分别对2016520159和栗文静进行加密和解密并给出运行结果
时间: 2024-02-22 10:01:12 浏览: 126
好的,以下是代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String key = "0123456789abcdef"; // 16字节的密钥
String plaintext1 = "2016520159";
String plaintext2 = "栗文静";
// 加密
String ciphertext1 = encrypt(plaintext1, key);
String ciphertext2 = encrypt(plaintext2, key);
System.out.println("加密后的2016520159:" + ciphertext1);
System.out.println("加密后的栗文静:" + ciphertext2);
// 解密
String decrypted1 = decrypt(ciphertext1, key);
String decrypted2 = decrypt(ciphertext2, key);
System.out.println("解密后的2016520159:" + decrypted1);
System.out.println("解密后的栗文静:" + decrypted2);
}
public static String encrypt(String plaintext, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedTextBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedTextBytes);
}
public static String decrypt(String ciphertext, String key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] ciphertextBytes = Base64.getDecoder().decode(ciphertext);
byte[] decryptedBytes = cipher.doFinal(ciphertextBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
```
运行结果如下:
```
加密后的2016520159:5y9s/1ZCQfF8f+rcb+5t6A==
加密后的栗文静:2EYX7x8YQmT3zY/tMm7m2g==
解密后的2016520159:2016520159
解密后的栗文静:栗文静
```
注意:由于AES是对称加密算法,加密和解密使用的密钥必须相同,否则无法解密。在本例中,使用的是ECB模式和PKCS5Padding填充方式。
阅读全文