DESC 加密解密

DESC 加密解密

package com.example.base.utils;

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

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 * @author Other
 */
public class DesUtil {

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

    /**
     * 加密解密算法
     */
    private final static String ALGORITHM = "DES";

    /**
     * 默认编码
     */
    private static final String DEFAULT_CHAR_SET = "UTF-8";

    /**
     * 加密解密KEY
     */
    private static final String KEY = "5e1de9b31ca44980905dba949869ccec";

    /**
     * 加密
     *
     * @param plaintext 未加密数据
     * @param key       加密key
     */
    public static String encrypt(String plaintext, String key) throws Exception {
        try {
            byte[] dataBytes = plaintext.getBytes(DEFAULT_CHAR_SET);
            byte[] keyBytes = key.getBytes(DEFAULT_CHAR_SET);

            SecretKey secretKey = getSecretKey(keyBytes);
            SecureRandom random = getSecureRandom();
            Cipher cipher = getCipher();

            // 用密匙初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);

            // 正式执行加密操作
            byte[] bytes = cipher.doFinal(dataBytes);
            return byte2hex(bytes);
        } catch (Exception e) {
            logger.error("method=encrypt() is error, error_msg:{}, error:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param ciphertext 加密后的数据
     * @param key        加密key
     * @return
     * @throws Exception
     */
    private static String decrypt(String ciphertext, String key) throws Exception {

        try {
            byte[] dataBytes = ciphertext.getBytes(DEFAULT_CHAR_SET);
            byte[] hex2byte = hex2byte(dataBytes);
            byte[] keyBytes = key.getBytes(DEFAULT_CHAR_SET);

            SecretKey secretKey = getSecretKey(keyBytes);
            SecureRandom random = getSecureRandom();
            Cipher cipher = getCipher();

            // 用密匙初始化Cipher对象
            cipher.init(Cipher.DECRYPT_MODE, secretKey, random);

            // 正式执行解密操作
            byte[] doFinal = cipher.doFinal(hex2byte);

            return new String(doFinal, DEFAULT_CHAR_SET);
        } catch (Exception e) {
            logger.error("method=encrypt() is error, error_msg:{}, error:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * DES算法要求有一个可信任的随机数源
     */
    private static SecureRandom getSecureRandom() throws Exception {
        return new SecureRandom();
    }

    /**
     * 创建一个密匙工厂,然后用它把DESKeySpec对象转换成一个SecretKey对象
     */
    private static SecretKey getSecretKey(byte[] keyBytes) throws Exception {
        // 从原始密匙数据创建一个DESKeySpec对象
        DESKeySpec dks = new DESKeySpec(keyBytes);
        // 创建一个密匙工厂,然后用它把DESKeySpec对象转换成一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    /**
     * Cipher对象实际完成解密操作
     */
    private static Cipher getCipher() throws Exception {
        return Cipher.getInstance(ALGORITHM);
    }

    /**
     * 把16进制字符串转换成字节数组
     */
    private static byte[] hex2byte(byte[] bytes) throws Exception {
        final int temp = 2;
        if ((bytes.length % temp) != 0) {
            throw new IllegalArgumentException("长度不是偶数");
        }
        byte[] bte = new byte[bytes.length / temp];
        for (int n = 0; n < bytes.length; n += temp) {
            String item = new String(bytes, n, temp, DEFAULT_CHAR_SET);
            bte[n / temp] = (byte) Integer.parseInt(item, 16);
        }
        return bte;
    }

    /**
     * 把字节数组转换成16进制字符串
     */
    private static String byte2hex(byte[] bytes) throws Exception {
        StringBuilder bulid = new StringBuilder();
        String stmp;
        for (byte bte : bytes) {
            stmp = (Integer.toHexString(bte & 0XFF));
            if (stmp.length() == 1) {
                bulid.append("0").append(stmp);
            } else {
                bulid.append(stmp);
            }
        }
        return bulid.toString();
    }

    public static void main(String[] args) throws Exception {
        String content = "这是一个测试";
        String str = DesUtil.encrypt(content, KEY);
        System.out.println("plaintext: " + str);
        str = DesUtil.decrypt(str, KEY);
        System.out.println("ciphertext: " + str);
    }

}


  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值