package encrypt; import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder; import javax.crypto.Cipher;
import javax.crypto.KeyGenerator; public class DESUtil {
private static Key key;
private static String KEY_STR="myKey";//密钥
static{
try {
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom(KEY_STR.getBytes()));
key = generator.generateKey();
generator=null;
} catch (Exception e) { }
} public static String getEncryptString(String str){
Encoder base64Encoder = Base64.getEncoder();
try {
byte[] strBytes = str.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptStrBytes = cipher.doFinal(strBytes);
return base64Encoder.encodeToString(encryptStrBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public static String getDecryptString(String str){
Decoder base64Decoder = Base64.getDecoder();
try {
byte[] strBytes = base64Decoder.decode(str);
Cipher cipher = Cipher.getInstance("DES");
cipher.init(cipher.DECRYPT_MODE, key);
byte[] decryptStrBytes = cipher.doFinal(strBytes);
return new String(decryptStrBytes,"UTF-8");
} catch (Exception e) {
}
return null; }
public static void main(String[] args) {
System.out.println(DESUtil.getEncryptString("147258"));
System.out.println(DESUtil.getDecryptString("VUhJSh5OPvI="));
}
} https://www.cnblogs.com/wulm/p/6907197.html