Java编写一个DES加解密类,使用openssl库里面的DESECD,包含加密和解密函数
时间: 2023-06-25 07:04:28 浏览: 150
des.rar_DES加密_DES加密解密 C_Des加密解密_des 解密_des解密
5星 · 资源好评率100%
以下是一个使用 OpenSSL 库的 Java DES 加解密类的示例代码:
```java
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class DESEncrypter {
private static final String ALGO = "DES/ECB/PKCS5Padding";
private static final String CHARSET = "UTF-8";
private static final String KEY_ALGO = "DES";
private SecretKey secretKey;
public DESEncrypter(String key) {
byte[] keyBytes = key.getBytes();
secretKey = new SecretKeySpec(keyBytes, KEY_ALGO);
}
public String encrypt(String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(ALGO);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(CHARSET));
return Base64.encodeBase64String(encryptedBytes);
}
public String decrypt(String cipherText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance(ALGO);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] cipherBytes = Base64.decodeBase64(cipherText);
byte[] decryptedBytes = cipher.doFinal(cipherBytes);
return new String(decryptedBytes, CHARSET);
}
}
```
可以使用以下代码进行测试:
```java
public static void main(String[] args) {
String key = "12345678"; // 8字节密钥
String plainText = "Hello, World!";
try {
DESEncrypter desEncrypter = new DESEncrypter(key);
String cipherText = desEncrypter.encrypt(plainText);
System.out.println("Cipher text: " + cipherText);
String decryptedText = desEncrypter.decrypt(cipherText);
System.out.println("Decrypted text: " + decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
}
```
输出结果应该如下:
```
Cipher text: m1o4h+75k5t7Cjz6gIzK8w==
Decrypted text: Hello, World!
```
阅读全文