java实现des加密
时间: 2023-11-18 10:50:42 浏览: 91
以下是Java实现DES加密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DES {
private static final String ALGORITHM = "DES";
public static byte[] encrypt(byte[] key, byte[] data) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
public static byte[] decrypt(byte[] key, byte[] data) throws Exception {
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(data);
}
}
```
使用示例:
```java
public static void main(String[] args) throws Exception {
byte[] key = "12345678".getBytes();
byte[] data = "hello world".getBytes();
byte[] encryptedData = DES.encrypt(key, data);
byte[] decryptedData = DES.decrypt(key, encryptedData);
System.out.println("Original data: " + new String(data));
System.out.println("Encrypted data: " + new String(encryptedData));
System.out.println("Decrypted data: " + new String(decryptedData));
}
```
阅读全文