DES加密算法java实现代码
时间: 2023-04-09 09:03:53 浏览: 221
以下是一个简单的DES加密算法的Java实现代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class DES {
private static final String ALGORITHM = "DES";
public static byte[] encrypt(byte[] input, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(input);
}
public static byte[] decrypt(byte[] input, byte[] key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return cipher.doFinal(input);
}
public static byte[] generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(56);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
}
}
```
这个代码可以用来加密和解密数据,同时也可以生成一个随机的DES密钥。
阅读全文