DecryptUtils.java 2.45 KB
package com.topdraw.dockingapi.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;

/**
 * 加解密工具
 *
 * @author chenwl
 * @date 2020-11-08 12:36:47
 */
public abstract class DecryptUtils {

    private static final Logger log = LoggerFactory.getLogger(DecryptUtils.class);
    private static final String TRANSFORMATION_DES = "DES/ECB/PKCS5Padding";
    private static final String ALGORITHM_DES = "DES";

    /**
     * DES 加密
     *
     * @param key       密钥,长度不能够小于8位字节
     * @param plainText 明文
     * @return 密文
     */
    public static String encode(String key, String plainText) throws Exception {
        return encode(key, plainText.getBytes());
    }

    /**
     * DES 加密
     *
     * @param key        密钥,长度不能够小于8位字节
     * @param plainBytes 明文字节数组
     * @return 密文
     */
    public static String encode(String key, byte[] plainBytes) throws Exception {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM_DES);
        Key secretKey = skf.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION_DES);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(plainBytes);
        return new String(Base64.encodeBase64(bytes));
    }

    /**
     * 解密
     *
     * @param key        密钥,长度不能够小于8位字节
     * @param cipherText 密文
     * @return 明文
     */
    public static String decode(String key, String cipherText) throws Exception {
        return decode(key, cipherText.getBytes());
    }

    /**
     * DES 解密
     *
     * @param key         密钥,长度不能够小于8位字节
     * @param cipherBytes 密文字节数组
     * @return 明文
     */
    private static String decode(String key, byte[] cipherBytes) throws Exception {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM_DES);
        Key secretKey = skf.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION_DES);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.decodeBase64(cipherBytes)));
    }


}