对称加密算法—3DES的代码用java
时间: 2023-12-11 19:02:58 浏览: 33
以下是使用Java实现3DES加密和解密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class TripleDesExample {
public static void main(String[] args) throws Exception {
// 生成随机密钥
byte[] keyBytes = new byte[24];
SecureRandom random = new SecureRandom();
random.nextBytes(keyBytes);
SecretKeySpec key = new SecretKeySpec(keyBytes, "DESede");
// 明文
String plaintext = "This is a secret message.";
// 加密
Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
byte[] ivBytes = new byte[8];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
// 解密
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] decryptedPlaintext = cipher.doFinal(ciphertext);
System.out.println("Key: " + Base64.getEncoder().encodeToString(keyBytes));
System.out.println("Plaintext: " + plaintext);
System.out.println("Ciphertext: " + Base64.getEncoder().encodeToString(ciphertext));
System.out.println("Decrypted plaintext: " + new String(decryptedPlaintext, StandardCharsets.UTF_8));
}
}
```
输出结果:
```
Key: 2qoQdkfT+i6JgMgkPyJQbV5bTq55X15f
Plaintext: This is a secret message.
Ciphertext: 2g3Mz0qKxGfz7NzE9wWx3uUqD2kQpWQb3RZ1MZq2+1M=
Decrypted plaintext: This is a secret message.
```
注意:使用3DES算法需要使用Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files来解除限制。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)