All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zcj.util.secret.UtilDes Maven / Gradle / Ivy

package com.zcj.util.secret;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * DES 对称加密算法
 *
 * @author [email protected]
 * @since 2020/12/10
 */
public class UtilDes {

    private static final Logger logger = LoggerFactory.getLogger(UtilDes.class);

    private static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";
    private static IvParameterSpec IV_SPEC = new IvParameterSpec("12345678".getBytes());

    /**
     * 加密
     *
     * @param key  * 秘钥
     * @param data * 待加密字符串
     * @return 密文;如果加密错误则返回NULL
     */
    public static String encode(String key, String data) {
        if (data == null || key == null) {
            return null;
        }
        try {
            DESKeySpec dks = new DESKeySpec(fillEightByte(key));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, IV_SPEC);
            byte[] bytes = cipher.doFinal(data.getBytes());
            return UtilHex.byteArrayToHex(bytes);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 解密
     *
     * @param key  * 秘钥
     * @param data * 待解密字符串
     * @return 解密后的内容
     */
    public static String decode(String key, String data) {
        if (data == null || key == null) {
            return null;
        }
        try {
            DESKeySpec dks = new DESKeySpec(fillEightByte(key));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, IV_SPEC);
            return new String(cipher.doFinal(UtilHex.hexToByteArray(data)));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    // 填充8个字节
    private static byte[] fillEightByte(String key) {
        byte[] base = key.getBytes();
        if (base.length >= 8) {
            return base;
        }
        byte[] result = new byte[8];
        System.arraycopy(base, 0, result, 0, base.length);
        return result;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy