Java实现DES加密解密算法,从键盘输入明文密文
时间: 2024-06-19 08:02:45 浏览: 182
Java可以使用JCE(Java Cryptography Extension)提供的API实现DES加密解密算法,以下是一个简单的示例:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Scanner;
public class DesDemo {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入明文:");
String plainText = scanner.nextLine();
System.out.print("请输入密钥(8个字符):");
String key = scanner.nextLine();
byte[] encrypted = encrypt(plainText, key);
System.out.println("加密后的密文:" + new String(encrypted));
String decrypted = decrypt(encrypted, key);
System.out.println("解密后的明文:" + decrypted);
}
private static byte[] encrypt(String plainText, String key) throws Exception {
// 生成密钥
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
// 加密
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return encrypted;
}
private static String decrypt(byte[] encrypted, String key) throws Exception {
// 生成密钥
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
// 解密
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted);
}
}
```
在上述代码中,我们通过 `KeyGenerator` 生成了一个 DES 密钥,并使用 `Cipher` 对象实现了 DES 加密和解密。注意,为了确保安全性,DES 的密钥长度必须为 8 个字符,否则会抛出异常。
阅读全文