给我一个 des加密的java的类
时间: 2023-06-07 09:11:57 浏览: 51
好的,以下是一个基于DES加密的Java类的示例代码:
```java
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
public class DES {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DES_ENCRYPTION_SCHEME = "DES";
private KeySpec myKeySpec;
private SecretKeyFactory mySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public DES() throws Exception
{
myEncryptionKey = "ThisIsSecretEncryptionKey";
myEncryptionScheme = DES_ENCRYPTION_SCHEME;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec = new DESKeySpec(keyAsBytes);
mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = mySecretKeyFactory.generateSecret(myKeySpec);
}
/**
* Method to encrypt a plain text string using DES algorithm
*
* @param unencryptedString
* @return encryptedString
*/
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.getEncoder().encode(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
/**
* Method to decrypt an encrypted string using DES algorithm
*
* @param encryptedString
* @return decryptedString
*/
public String decrypt(String encryptedString) {
String decryptedText = null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.getDecoder().decode(encryptedString.getBytes());
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText = new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
public static void main(String args[]) {
try {
DES des = new DES();
System.out.println("Encryption Key: " + des.myEncryptionKey);
String sampleString = "This is example plain text and we will encrypt this using DES algorithm.";
String encryptedString = des.encrypt(sampleString);
System.out.println("Encrypted String: " + encryptedString);
String decryptedString = des.decrypt(encryptedString);
System.out.println("Decrypted String: " + decryptedString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意:该示例代码中的密钥是固定的,并不是安全的方式。在实际使用时,应该使用更加安全的方式来生成和管理密钥。