java实现des加解密算法
时间: 2023-05-29 20:05:39 浏览: 53
以下是Java实现DES加解密算法的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class DesDemo {
private static final String KEY = "12345678"; // 密钥
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!"; // 明文
String encryptedText = encrypt(plainText); // 加密
System.out.println("加密后的密文:" + encryptedText);
String decryptedText = decrypt(encryptedText); // 解密
System.out.println("解密后的明文:" + decryptedText);
}
// DES加密
private static String encrypt(String plainText) throws Exception {
// 创建DESKeySpec对象
DESKeySpec desKeySpec = new DESKeySpec(KEY.getBytes(StandardCharsets.UTF_8));
// 创建SecretKeyFactory对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 生成SecretKey对象
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// 创建Cipher对象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
// 加密
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
// Base64编码
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// DES解密
private static String decrypt(String encryptedText) throws Exception {
// 创建DESKeySpec对象
DESKeySpec desKeySpec = new DESKeySpec(KEY.getBytes(StandardCharsets.UTF_8));
// 创建SecretKeyFactory对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
// 生成SecretKey对象
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
// 创建Cipher对象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
// Base64解码
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
// 解密
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}
```
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)