欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

加密算法 - DES

程序员文章站 2024-03-14 11:02:46
...

加密算法 - DES

/**
 * DES
 * @author
 */
@Slf4j
@Component
public class DESUtil {

    private static final String ALGORITHM = "DESede";
    
    public static String key;

    // 配置文件,配置**,也可以写死一个 String key = "";
    @Autowired
    private CustomPropertiesConfig systemPropertiesConfig;

    @PostConstruct
    public void init() {
        // 从配置文件读取,区分不同环境
        key = systemPropertiesConfig.getDesKey();
    }

    private DESUtil() {

    }

    /**
     * 生成**
     * @param key
     * @return
     */
    public static String generateKey(String key) {
        SecretKey secretKey = generateSecretKey(key);
        return new String(secretKey.getEncoded());
    }

/**
     * 生成**
     * @param key
     * @return
     */
    private static SecretKey generateSecretKey(String key) {
        SecretKey secretKey = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = key.getBytes();
            md.update(bytes, 0, bytes.length);
            // Generate 16 bytes whenever
            byte[] mdBytes = md.digest();
            // Generate 24 bytes for DESedeKeySpec
            byte[] encodedBytes = Base64.encodeBase64(mdBytes);
            DESedeKeySpec keySpec = new DESedeKeySpec(encodedBytes);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            secretKey = keyFactory.generateSecret(keySpec);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return secretKey;
    }

    /**
     * 3DES加密
     * @param str    加密的字符串
     * @return
     */
    public static String encode3Des(String str) throws Exception{
        byte[] bytes = toHexByte(key);
        byte[] strBytes = str.getBytes();
        try {
            //生成**
            SecretKey secretKey = new SecretKeySpec(bytes, ALGORITHM);
            //加密
            Cipher c1 = Cipher.getInstance(ALGORITHM);
            c1.init(Cipher.ENCRYPT_MODE, secretKey);

            return Base64.encodeBase64String(c1.doFinal(strBytes));
        } catch (NoSuchAlgorithmException e1) {
            log.error("encode3Des NoSuchAlgorithmException error:{}", e1.getMessage());
            throw new Exception(-1, "加密时,没有找到指定的加密算法");
        } catch(Exception e3) {
            log.error("encode3Des error:{}", e3.getMessage());
            throw new Exception(-1, "数据加密异常");
        }
    }

    /**
     * 解密
     * @param desStr
     * @return
     */
    public static String decode3Des(String desStr) throws Exception{
        Base64 base64 = new Base64();
        byte[] bytes = toHexByte(key);
        byte[] desStrBytes = base64.decode(desStr);
        try {
            //生成**
            SecretKey secretKey = new SecretKeySpec(bytes, ALGORITHM);
            //解密
            Cipher c1 = Cipher.getInstance(ALGORITHM);
            c1.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(c1.doFinal(desStrBytes));
        } catch (NoSuchAlgorithmException e1) {
            log.error("decode3Des NoSuchAlgorithmException error:{}", e1.getMessage());
            throw new Exception(-1, "解密时,没有找到指定的加密算法");
        } catch(Exception e3) {
            log.error("decode3Des error:{}", e3.getMessage());
            throw new Exception(-1, "数据解密异常");
        }
    }

    /**
     *
     * @param key
     * @return
     */
    public static byte[] toHexByte(String key) {
        String f = DigestUtils.md5Hex(key);
        byte[] keysByte = f.getBytes();
        byte[] result = new byte[24];
        for (int i=0; i < 24; i++){
            result[i] = keysByte[i];
        }

        return result;
    }

**生成方法,仅供参考,自定义key都行

public static void main(String[] args) {
        String key = UUID.randomUUID().toString();
        System.out.println(generateKey(key));
}