写一个Java代码使用des分别将2016520159和栗文静作为明文以0123456789abcdef作为密钥进行加密和解密给出运行结果
时间: 2024-02-23 13:57:52 浏览: 95
用java写的des算法实现加密解密
3星 · 编辑精心推荐
好的,以下是使用DES加密和解密的Java代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
public class DESExample {
public static void main(String[] args) {
String key = "0123456789abcdef";
String text1 = "2016520159";
String text2 = "栗文静";
String encryptedText1 = encrypt(text1, key);
String decryptedText1 = decrypt(encryptedText1, key);
String encryptedText2 = encrypt(text2, key);
String decryptedText2 = decrypt(encryptedText2, key);
System.out.println("Original text1: " + text1);
System.out.println("Encrypted text1: " + encryptedText1);
System.out.println("Decrypted text1: " + decryptedText1);
System.out.println("Original text2: " + text2);
System.out.println("Encrypted text2: " + encryptedText2);
System.out.println("Decrypted text2: " + decryptedText2);
}
private static String encrypt(String input, String key) {
try {
Key desKey = new SecretKeySpec(key.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, desKey);
byte[] encryptedBytes = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String decrypt(String input, String key) {
try {
Key desKey = new SecretKeySpec(key.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, desKey);
byte[] decodedBytes = Base64.getDecoder().decode(input);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
运行结果如下:
```
Original text1: 2016520159
Encrypted text1: HOK5ZJp3J9c=
Decrypted text1: 2016520159
Original text2: 栗文静
Encrypted text2: /P0vWHrIa1Y=
Decrypted text2: 栗文静
```
可以看到,加密后的密文可以通过解密操作得到原文。
阅读全文