java des/ebc/zeros 加解密
时间: 2023-06-30 12:26:05 浏览: 69
以下是Java中采用DES对称加密算法,ECB加密模式,补0填充方式进行加密和解密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class DesEcbZeroPaddingExample {
public static void main(String[] args) throws Exception {
String plaintext = "hello world";
String key = "12345678";
// 加密
byte[] encrypted = desEcbZeroPaddingEncrypt(plaintext.getBytes(), key.getBytes());
System.out.println("加密后的密文:" + new String(encrypted));
// 解密
byte[] decrypted = desEcbZeroPaddingDecrypt(encrypted, key.getBytes());
System.out.println("解密后的明文:" + new String(decrypted));
}
public static byte[] desEcbZeroPaddingEncrypt(byte[] plaintext, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(plaintext);
}
public static byte[] desEcbZeroPaddingDecrypt(byte[] ciphertext, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(ciphertext);
}
}
```
需要注意的是,补0填充方式可能会导致加密后的密文长度不是8字节的倍数,需要在解密后去除填充数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)