des算法java代码实现密钥明文用户输入
时间: 2023-08-05 14:04:49 浏览: 108
DES.zip_6PEE_des_des代码实现_fogrdd_密码学
以下是DES算法的Java代码实现,其中包括了密钥和明文的用户输入:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Scanner;
public class DES {
private static final String ALGORITHM = "DES";
private static final String MODE = "ECB";
private static final String PADDING = "PKCS5Padding";
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
// 获取密钥
System.out.print("请输入8位密钥:");
String key = scanner.nextLine();
byte[] keyBytes = key.getBytes();
// 获取明文
System.out.print("请输入明文:");
String plaintext = scanner.nextLine();
byte[] plaintextBytes = plaintext.getBytes();
// 加密
byte[] ciphertextBytes = encrypt(keyBytes, plaintextBytes);
// 将密文转换为Base64字符串
String ciphertext = Base64.getEncoder().encodeToString(ciphertextBytes);
System.out.println("加密后的密文:" + ciphertext);
// 解密
byte[] decryptedBytes = decrypt(keyBytes, Base64.getDecoder().decode(ciphertext));
// 将解密后的明文转换为字符串
String decryptedPlaintext = new String(decryptedBytes);
System.out.println("解密后的明文:" + decryptedPlaintext);
}
/**
* 加密
*
* @param keyBytes 密钥
* @param plaintextBytes 明文
* @return 密文
* @throws Exception
*/
public static byte[] encrypt(byte[] keyBytes, byte[] plaintextBytes) throws Exception {
SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/" + PADDING);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(plaintextBytes);
}
/**
* 解密
*
* @param keyBytes 密钥
* @param ciphertextBytes 密文
* @return 明文
* @throws Exception
*/
public static byte[] decrypt(byte[] keyBytes, byte[] ciphertextBytes) throws Exception {
SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM + "/" + MODE + "/" + PADDING);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(ciphertextBytes);
}
}
```
在这个实现中,我们使用了Java中的`Scanner`来获取用户输入的密钥和明文。我们将密钥和明文都转换为字节数组,然后调用`encrypt`方法加密,再将密文转换为Base64字符串输出。接着,我们调用`decrypt`方法解密密文,将解密后的明文转换为字符串输出。
阅读全文