前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >3DES,32位长秘钥加密

3DES,32位长秘钥加密

作者头像
py3study
发布2020-01-08 17:08:47
1.5K0
发布2020-01-08 17:08:47
举报
文章被收录于专栏:python3python3

一般3des加密的秘钥是一个24位的字节数组,但是很多遇到32位字符串秘钥,不知道怎么去用,其实只是经过几步转化就可以了。希望这篇文章对大家有帮助或者带来灵感

比如:

秘钥:33333333333333333333333333333333

要加密内容:06111111FFFFFFFF

加密后内容:66322DAA27A95807

java代码

代码语言:javascript
复制
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import com.raying.abs.base.logger.Logger;
/**
 * 3DES加密工具类
 * @author QiaoZhenwu
 */
public class Des3EncryptUtils {
    /** 密钥 */
    private SecretKey securekey;
    /**
     * setKey(设置byte[] KEY值) (算法中需要通过key来得到加密用的key)
     */
    public void setKey(byte[] key) {
        try {
            DESedeKeySpec dks = new DESedeKeySpec(key);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
            securekey = keyFactory.generateSecret(dks);
        } catch (Exception e) {
            Logger.error(e.getMessage(), e);
        }
    }
    /**
     * get3DesEncCode(3DesECB加密byte[]明文)
     */
    public byte[] get3DesEncCode(byte[] byteS) {
        byte[] byteFina = null;
        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DESede/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, securekey);
            byteFina = cipher.doFinal(byteS);
        } catch (Exception e) {
          Logger.error(e.getMessage(), e);
        } finally {
            cipher = null;
        }
        return byteFina;
    }
    /**
     * get3DesDesCode(3DesECB解密byte[]密文)
     */
    public byte[] get3DesDesCode(byte[] byteD) {
        Cipher cipher;
        byte[] byteFina = null;
        try {
            cipher = Cipher.getInstance("DESede/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, securekey);
            byteFina = cipher.doFinal(byteD);
        } catch (Exception e) {
          Logger.error(e.getMessage(), e);
        } finally {
            cipher = null;
        }
        return byteFina;
    }
}

/**
 * 3DES加解密主类,加解密调用内部的方法
 * @author QiaoZhenwu
 *
 */
public class Des3Utils {
     /**
     * dec:(解密).
     * @param key 密钥
     * @param content 密文内容 16位
     * @return 返回结果:String
     */
    public static String decryption(String key, String content) {
        Des3EncryptUtils des = new Des3EncryptUtils();
        String enKey = "";//最终解密秘钥 48位
        String enContent = "";//解密内容
        if(key.length() <= 32){
          enKey = (key + key).substring(0, 48);
        }else if(key.length() >= 48){
          enKey = key.substring(0, 48);
        }
        if(content.length() == 16){
          enContent = content;
        }else{
          if(content.length() > 16){
              throw new RuntimeException("the encrypt content length more than 16");
          }else if(content.length() < 16){
              throw new RuntimeException("the encrypt content length less than 16");
          }
        }
        des.setKey(enKey.getBytes());
        byte[] get3DesDesCode = des.get3DesDesCode(HexUtils.fromString(enContent));
        return HexUtils.toString(get3DesDesCode).trim();
    }
   
   
    /**
     * dec:(加密).
     * @param key 密钥
     * @param content  密文内容 16位
     * @return 返回结果:String
     */
    public static String encryption(String key, String content) {
        Des3EncryptUtils des = new Des3EncryptUtils();
        String enKey = "";//最终加密秘钥48位
        String enContent = "";//加密内容
        if(key.length() <= 32){
          enKey = (key + key).substring(0, 48);
        }else if(key.length() >= 48){
          enKey = key.substring(0, 48);
        }
        if(content.length() == 16){
          enContent = content;
        }else{
          if(content.length() > 16){
              throw new RuntimeException("the encrypt content length more than 16");
          }else if(content.length() < 16){
              throw new RuntimeException("the encrypt content length less than 16");
          }
        }
        des.setKey(enKey.getBytes());
        byte[] bye = des.get3DesEncCode(HexUtils.fromString(enContent));
        return HexUtils.toString(bye).trim();
    }
}


/**
 * 十六进制帮助类
 * @author QiaoZhenwu
 */
public class HexUtils {
    /** 转换数据 */
    private static final char[] HEXDIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    /**
     * toString(控制长度的将byte[]的转换为相应的十六进制String表示)
     */
    public static String toString(byte[] ba, int offset, int length) {
        char[] buf = new char[length * 2];
        int j = 0;
        int k;
        for (int i = offset; i < offset + length; i++) {
            k = ba[i];
            buf[j++] = HEXDIGITS[(k >>> 4) & 0x0F];
            buf[j++] = HEXDIGITS[k & 0x0F];
        }
        return new String(buf);
    }
    /**
     * toString(将byte[]的转换为相应的十六进制String表示)
     */
    public static String toString(byte[] ba) {
        return toString(ba, 0, ba.length);
    }
    /**
     * fromString(将十六进制形式的字符串转换为byte[])
     */
    public static byte[] fromString(String hex) {
        int len = hex.length();
        byte[] buf = new byte[(len + 1) / 2];
        int i = 0;
        int j = 0;
        if ((len % 2) == 1) {
            buf[j++] = (byte) fromDigit(hex.charAt(i++));
        }
        while (i < len) {
            buf[j++] = (byte) ((fromDigit(hex.charAt(i++)) << 4) | fromDigit(hex.charAt(i++)));
        }
        return buf;
    }
    /**
     * fromDigit(将十六进制的char转换为十进制的int值)
     */
    public static int fromDigit(char ch) {
        if (ch >= '0' && ch <= '9') {
            return ch - '0';
        }
        if (ch >= 'A' && ch <= 'F') {
            return ch - 'A' + 10;
        }
        if (ch >= 'a' && ch <= 'f') {
            return ch - 'a' + 10;
        }
        throw new IllegalArgumentException("invalid hex digit '" + ch + "'");
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档