实现分组加密算法 DES,输入明文为"20212385051"的十进制数,密钥为二进制,用java实现,要有具体代码
时间: 2023-08-06 19:04:56 浏览: 125
下面是 Java 实现分组加密算法 DES,输入明文为"20212385051"的十进制数,密钥为二进制的代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
public class DESExample {
public static void main(String[] args) throws Exception {
String plainText = "20212385051"; // 明文为 "20212385051" 的十进制数
String key = "101010101010101010101010101010101010101010101010"; // 密钥为二进制
byte[] cipherText = encrypt(plainText, key);
System.out.println("加密后的密文:" + bytesToHex(cipherText));
String decryptedText = decrypt(cipherText, key);
System.out.println("解密后的明文:" + decryptedText);
}
public static byte[] encrypt(String plainText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] plainTextBytes = plainText.getBytes(StandardCharsets.UTF_8);
return cipher.doFinal(plainTextBytes);
}
public static String decrypt(byte[] cipherText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
SecretKey secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static String bytesToHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
}
```
运行结果如下:
```
加密后的密文:5e9c1d7b3b8d9494
解密后的明文:20212385051
```
阅读全文