des加密接口
时间: 2023-08-30 18:05:46 浏览: 86
以下是一个使用Java实现DES加密的例子:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
public class DES {
public static void main(String[] args) throws Exception {
String plainText = "Hello, World!";
String key = "12345678"; // 8字节的密钥
byte[] encrypted = encrypt(plainText, key);
System.out.println("加密后的结果:" + new String(encrypted));
String decrypted = decrypt(encrypted, key);
System.out.println("解密后的结果:" + decrypted);
}
public static byte[] encrypt(String plainText, String key) throws Exception {
Key secretKey = new SecretKeySpec(key.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] encrypted, String key) throws Exception {
Key secretKey = new SecretKeySpec(key.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted);
}
}
```
在这个例子中,我们使用了Java提供的`javax.crypto`库来实现DES加密。`encrypt`方法接收一个明文和一个密钥,并返回加密后的结果。`decrypt`方法接收一个加密后的字节数组和一个密钥,并返回解密后的明文。在这个例子中,我们使用了ECB工作模式和PKCS5Padding填充方式。
阅读全文
相关推荐


















