java实现des加解密算法
时间: 2023-09-29 15:09:57 浏览: 150
Java中实现DES加解密算法可以使用Java内置的Cipher类实现。以下是一个简单的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class DES {
private static final String ALGORITHM = "DES";
private static final String TRANSFORMATION = "DES/ECB/PKCS5Padding";
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return cipher.doFinal(data);
}
public static void main(String[] args) throws Exception {
String keyStr = "12345678";
byte[] key = keyStr.getBytes();
String dataStr = "Hello, DES";
byte[] data = dataStr.getBytes();
byte[] encryptedData = encrypt(data, key);
System.out.println("Encrypted data: " + new String(encryptedData));
byte[] decryptedData = decrypt(encryptedData, key);
System.out.println("Decrypted data: " + new String(decryptedData));
}
}
```
在上面的示例代码中,encrypt()方法和decrypt()方法分别用于加密和解密数据。其中,key参数为加密密钥,data参数为待加密或解密的数据。示例代码中使用的加密模式为ECB,填充方式为PKCS5Padding。在实际应用中,应该根据具体需求选择合适的加密模式和填充方式。
阅读全文