des加密 java实现
时间: 2023-11-18 21:48:50 浏览: 120
以下是Java实现DES加密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
public class DESUtil {
private static final String ALGORITHM = "DES";
/**
* 生成DES密钥
*
* @return 密钥字符串
*/
public static String generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(56); // DES密钥长度为56位
SecretKey secretKey = keyGenerator.generateKey();
return Base64Util.encode(secretKey.getEncoded());
}
/**
* 加密
*
* @param plainText 明文字符串
* @param key 密钥字符串
* @return 密文字符串
*/
public static String encrypt(String plainText, String key) throws Exception {
Key desKey = new SecretKeySpec(Base64Util.decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, desKey);
byte[] cipherBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
return Base64Util.encode(cipherBytes);
}
/**
* 解密
*
* @param cipherText 密文字符串
* @param key 密钥字符串
* @return 明文字符串
*/
public static String decrypt(String cipherText, String key) throws Exception {
Key desKey = new SecretKeySpec(Base64Util.decode(key), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, desKey);
byte[] plainBytes = cipher.doFinal(Base64Util.decode(cipherText));
return new String(plainBytes, StandardCharsets.UTF_8);
}
}
```
其中,Base64Util是一个Base64编码工具类,可以自行实现或引用第三方库。
使用示例:
```java
public class Main {
public static void main(String[] args) throws Exception {
String plainText = "Hello, DES!";
String key = DESUtil.generateKey();
System.out.println("密钥:" + key);
String cipherText = DESUtil.encrypt(plainText, key);
System.out.println("密文:" + cipherText);
String decryptedText = DESUtil.decrypt(cipherText, key);
System.out.println("解密后的明文:" + decryptedText);
}
}
```
输出:
```
密钥:m8+0AcgYvJw=
密文:mHgl8OZC+6U=
解密后的明文:Hello, DES!
```
阅读全文