des加解密算法java代码实现密钥明文用户输入密钥为16个16进制数,明文也为16个16进制数
时间: 2024-02-06 17:09:37 浏览: 164
下面是 DES 加解密算法的 Java 代码实现,包括密钥和明文输入:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.util.Scanner;
public class DesEncryption {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
// 获取密钥
System.out.print("请输入16个16进制数作为密钥:");
String keyHex = scanner.nextLine();
byte[] keyBytes = hexStringToByteArray(keyHex);
DESKeySpec desKeySpec = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// 获取明文
System.out.print("请输入16个16进制数作为明文:");
String plaintextHex = scanner.nextLine();
byte[] plaintextBytes = hexStringToByteArray(plaintextHex);
// 加密
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] ciphertextBytes = cipher.doFinal(plaintextBytes);
String ciphertextHex = byteArrayToHexString(ciphertextBytes);
System.out.println("加密后的密文为:" + ciphertextHex);
// 解密
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(ciphertextBytes);
String decryptedHex = byteArrayToHexString(decryptedBytes);
System.out.println("解密后的明文为:" + decryptedHex);
}
/**
* 将十六进制字符串转换为字节数组
*/
public static byte[] hexStringToByteArray(String hexString) {
int len = hexString.length();
byte[] bytes = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i + 1), 16));
}
return bytes;
}
/**
* 将字节数组转换为十六进制字符串
*/
public static String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
}
```
使用时,先输入 16 个 16 进制数作为密钥,然后输入 16 个 16 进制数作为明文。程序会输出加密后的密文和解密后的明文。注意,此代码使用的是 DES/ECB/NoPadding 加密模式,即 ECB 模式下不使用填充。如果需要使用其他模式或填充方式,请根据实际情况修改代码。
阅读全文