123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- package com.kxs.adminap.util;
- import java.nio.charset.StandardCharsets;
- import java.security.Key;
- import java.security.SecureRandom;
- import java.util.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.KeyGenerator;
- import javax.crypto.SecretKeyFactory;
- import javax.crypto.spec.DESedeKeySpec;
- import javax.crypto.spec.IvParameterSpec;
- public class DesUtil {
- public static Key setKey(String strKey) {
- Key key = null;
- try {
- KeyGenerator generator = KeyGenerator.getInstance("DES");
- generator.init(new SecureRandom(strKey.getBytes())); // 根据参数生成key
- key = generator.generateKey();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return key;
- }
- /**
- * @param source
- * 编码内容
- * @param key
- * 密钥
- * @param charSet
- * 编码格式
- * @return
- */
- public static String encrypt(String source, String key, String charSet) {
- String encrypt = null;
- try {
- byte[] ret = encrypt(source.getBytes(charSet), key);
- encrypt = new String(Base64.getEncoder().encode(ret));
- } catch (Exception e) {
- e.printStackTrace();
- encrypt = null;
- }
- return encrypt;
- }
- /**
- * @param encryptedData
- * 解码内容
- * @param key
- * 密钥
- * @param charSet
- * 编码格式
- * @return
- */
- public static String decrypt(String encryptedData, String key, String charSet) {
- // String descryptedData = null;
- // try {
- // byte[] ret = descrypt(Base64.getDecoder().decode(encryptedData.getBytes(StandardCharsets.UTF_8)), key);
- // descryptedData = new String(ret, charSet);
- // } catch (Exception e) {
- // e.printStackTrace();
- // descryptedData = null;
- // }
- // return descryptedData;
- String result = "";
- try {
- Key desKey = setKey(key);
- Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
- cipher.init(Cipher.DECRYPT_MODE, desKey);
- byte[] base64Byte = Base64.getDecoder().decode(encryptedData);
- byte[] decryptData = cipher.doFinal(base64Byte);
- result = new String(decryptData, StandardCharsets.UTF_8);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- private static byte[] encrypt(byte[] primaryData, String key) {
- Key desKey = setKey(key);
- try {
- Cipher cipher = Cipher.getInstance("DES"); // Cipher对象实际完成加密操作
- cipher.init(Cipher.ENCRYPT_MODE, desKey); // 用密钥初始化Cipher对象(加密)
- return cipher.doFinal(primaryData);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- private static byte[] descrypt(byte[] encryptedData, String key) {
- Key desKey = setKey(key);
- try {
- Cipher cipher = Cipher.getInstance("DES"); // Cipher对象实际完成解密操作
- cipher.init(Cipher.DECRYPT_MODE, desKey); // 用密钥初始化Cipher对象(解密)
- return cipher.doFinal(encryptedData);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }
|