3DES,32位长秘钥加密

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

比如:

秘钥:33333333333333333333333333333333

要加密内容:06111111FFFFFFFF

加密后内容:66322DAA27A95807

java代码

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 + "‘");
    }
}
时间: 2024-12-21 01:31:19

3DES,32位长秘钥加密的相关文章

JAVA随机的32位长的字符串

CommonUtils类依赖的jar包:commons-beanutils.jar.commons-logging.jar uuid()方法 * 返回一个随机的32位长的字符串 * 用途: * 可以用来做id等各种不能重复的变量,数据库表中的主键不能重复的,它就是不重复的! @Test public void testUnid() { String s=CommonUtils.uuid(); System.out.println(s); } 作用:把一个map中的数据封装到javabean中 *

在Delphi中获得唯一32位长字符串

function GetGUID: string; var   vGUID: TGUID;   vTemp:string; begin   if S_OK = CreateGuid(vGUID) then   begin     vTemp := GUIDToString(vGUID);     //去掉字符串中的{,-字符     vTemp:=StringReplace(vTemp,'-','',[rfReplaceAll]);     vTemp:=StringReplace(vTemp,

APICloud集成支付宝--RSA秘钥生成详解

RSA 和 OpenSSL 介绍 记得大学里有门课叫<电子支付与安全>,这里面就讲了双重秘钥加密,主要内容如下: RSA 是一种非对称的签名算法,即签名密钥(私钥)与验签密钥(公钥)是不一样的, 私钥用于签名,公钥用于验签.在与支付宝交易中,会有 2 对公私钥,即商户公私钥,支付宝公私钥.使用这种算法可以起到防止数据被篡改的功能,保证支付订单和支付结果不可抵赖(商户私钥只有商户知道). OpenSSL 是基于众多的密码算法.公钥基础设施标准以及 SSL 协议安全开 发包.通过 OpenSSL

Number of 1 Bits (求32位二进制数中1的)

<span style="font-size:24px;"> </span> 1.题目: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). For example, the 32-bit integer '11' has binary representation

HTTPS 之共享秘钥 公钥 及 私钥

HTTPS 之共享秘钥 公钥 及 私钥一 共享秘钥1.1 概念共享秘钥和我们生活中同一把锁的钥匙概念类似,对同一把锁来说,加锁时使用什么钥匙,解锁也必须使用同样的钥匙. 1.2 共享秘钥在HTTP传输中的缺点以共享密钥方式加密时必须将密钥也发给对方.在互联网上转发密钥时,如果通信被监听,那么密钥就可会落入攻击者之手,同时也就失去了加密的意义.另外还得设法安全地保管接收到的密钥. 二 SSL(Secure Socket Layer)公开秘钥加密2.1 概念公开密钥加密使用一对非对称的密钥.一把叫做

如何通过抓包查看客户端https连接中ssl/tls加密所采用的秘钥位数

在https传输的过程中,我们底层的加密传输协议是ssl/tls.这里所使用的加密算法的秘钥位数(也就是服务器所使用的https证书的位数)可能是1024/2048或者更高,目前1024位的证书已经被证实是不安全的,需要逐步替换掉. 那么如何通过抓包来查看当前连接所采用的实际加密位数呢(注意,这里是抓包查看,如果是网页我们用浏览器直接访问,点击那个小锁然后进行一系列的操作就可以查看到连接信息了,如果有兴趣查看以下链接内容:http://www.wosign.com/FAQ/how_to_chec

SSH HTTPS 公钥、秘钥、对称加密、非对称加密、 总结理解

DES: Digital Encryption Standard. Obsolete standard. 单密钥算法,是信息的发送方采用密钥A进行数据加密,信息的接收方采用同一个密钥A进行数据解密. 单密钥算法是一个对称算法. 算法好在加/解速度快,密钥量短,采用对称加密 DSA: Digital Signature Algorithm. based on discrete logarithms computation. 用于签名 RSA: RSA 是一种非对称加解密算法. RSA 与 DSA

解决128位秘钥长度限制的方法

当秘钥长度超过128位(即16字符时),会加密失败,报"java.security.InvalidKeyException: Illegal key size or default parameters"的异常,因此需要去掉该限制 处理的方法由三种,分别是直接替换或是自定义classloader加载放开限制的jar或者通过反射移除限制 1.直接替换 比如java8的话,去orcle官网http://download.oracle.com/otn-pub/java/jce/8/jce_p

C# 字符串md5加密成16位和32位

#region md5加密 /// <summary> /// MD5 16位加密 加密后密码为小写 /// </summary> /// <param name="ConvertString"></param> /// <returns></returns> private string GetMd5Str16(string ConvertString) { try { using (MD5CryptoServi