Java编写一个能进行DESEDE加密解密的程序
时间: 2024-10-09 09:02:47 浏览: 60
在Java中编写DESEDE(三重DES,即Triple DES)加密解密程序,首先需要导入`javax.crypto.Cipher`和`java.security.Key`包。DESEDE是一种使用三个独立的DES密钥(一个主密钥和两个辅助密钥)来进行加密和解密的过程,提供更高的安全性。
以下是简单的DESEDE加密和解密示例:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class DESDESEncryption {
private static final String ALGORITHM = "DESede";
private static final byte[] KEY = "your_secret_key_128_chars".getBytes(); // 168位密钥
public static String encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec secretKey = new SecretKeySpec(KEY, ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
SecretKeySpec secretKey = new SecretKeySpec(KEY, ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedData);
}
public static void main(String[] args) {
try {
String originalText = "This is a test message.";
String encryptedText = encrypt(originalText);
System.out.println("Encrypted: " + encryptedText);
String decryptedText = decrypt(encryptedText);
System.out.println("Decrypted: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个例子中,你需要替换`"your_secret_key_128_chars"`为你的实际密钥,并注意,DESEDE通常用于短消息加密,因为它的速度较慢,适合对大量数据进行分块加密。
阅读全文
相关推荐


















