2019-04-21 22:05:15 sh879682 阅读数 335
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25413 人正在学习 去看看 邵发

DES/3DES属于对称加密算法。3des即用DES进行三重加密。

下面分别用Java代码实现DES加密解密与3DES加密解密,如有错误请指正,谢谢!

DES加密解密:

/**
 * DES加密
 * @param datasource,加密数据
 * @param password,密钥
 * @return
 */
public static  byte[] encrypt(byte[] datasource, String password) {
    try{
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        //创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");
        //用密匙初始化Cipher对象,ENCRYPT_MODE用于将 Cipher 初始化为加密模式的常量
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        //现在,获取数据并加密
        //正式执行加密操作
        return cipher.doFinal(datasource); //按单部分操作加密或解密数据,或者结束一个多部分操作
    }catch(Throwable e){
        e.printStackTrace();
    }
    return null;
}

DES解密

/**
 * DES解密
 * @param src 解密数据
 * @param password  密钥
 * @return
 * @throws Exception
 */
public static byte[] decrypt(byte[] src, String password) throws Exception {
    // DES算法要求有一个可信任的随机数源
    SecureRandom random = new SecureRandom();
    // 创建一个DESKeySpec对象
    DESKeySpec desKey = new DESKeySpec(password.getBytes());
    // 创建一个密匙工厂
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");//返回实现指定转换的 Cipher 对象
    // 将DESKeySpec对象转换成SecretKey对象
    SecretKey securekey = keyFactory.generateSecret(desKey);
    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance("DES");
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, securekey, random);
    // 真正开始解密操作
    return cipher.doFinal(src);
}

3DES加密

/**
 * 3DES加密
 * @param srcData,加密字符串
 * @param dESKey ,加密密钥
 * @return
 * @throws Exception
 */
public static String desEncrypt(String srcData, String dESKey)
        throws Exception
{
    SecureRandom sr = new SecureRandom();

    byte[] rawKeyData = DES.hexstr2ByteArr(dESKey);

    DESKeySpec dks = new DESKeySpec(rawKeyData);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");

    SecretKey key = keyFactory.generateSecret(dks);

    Cipher cipher = Cipher.getInstance("DESede");

    cipher.init(1, key, sr);

    byte[] data = srcData.getBytes("UTF8");

    byte[] encryptedData = cipher.doFinal(data);

    String enOut = DES.byteArr2HexStr(encryptedData);

    return enOut;
}

3DES解密

/**
 * 3DES解密
 * @param srcData
 * @param dESKey
 * @return
 * @throws Exception
 */
public static String desDecrypt(String srcData, String dESKey)
        throws Exception
{
    SecureRandom sr = new SecureRandom();

    byte[] rawKeyData = hexstr2ByteArr(dESKey);

    DESKeySpec dks = new DESKeySpec(rawKeyData);

    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");

    SecretKey key = keyFactory.generateSecret(dks);

    Cipher cipher = Cipher.getInstance("DESede");

    cipher.init(2, key, sr);

    byte[] data = hexstr2ByteArr(srcData);

    byte[] decryptedData = cipher.doFinal(data);

    String out = new String(decryptedData, "UTF8");

    return out;
}

HEX转byte

public static byte[] hexstr2ByteArr(String strIn)
{
    byte[] arrB = strIn.getBytes();

    int iLen = arrB.length;

    byte[] arrOut = new byte[iLen / 2];

    for (int i = 0; i < iLen; i += 2)
    {
        String strTmp = new String(arrB, i, 2);

        arrOut[(i / 2)] = (byte)Integer.parseInt(strTmp, 16);
    }

    return arrOut;
}

byte转HEX

public static String byteArr2HexStr(byte[] arrB)
        throws IOException
{
    int iLen = arrB.length;

    StringBuffer sb = new StringBuffer(iLen * 2);

    for (int i = 0; i < iLen; ++i)
    {
        int intTmp = arrB[i];

        while (intTmp < 0)
        {
            intTmp += 256;
        }

        if (intTmp < 16)
        {
            sb.append("0");
        }

        sb.append(Integer.toString(intTmp, 16));
    }

    return sb.toString();
}

 

2014-03-01 18:28:13 clh604 阅读数 27343
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25413 人正在学习 去看看 邵发

des加密是对称加密中在互联网应用的比较多的一种加密方式,php 通过mcrypt扩展库来支持des加密,要在Php中使用des加密,需要先安装mcrypt扩展库


下面是加密解密的实例


$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = "This is a very secret key";//密钥
$text = "Meet me at 11 o'clock behind the monument.";//需要加密的内容
echo ($text) . "\n";

$crypttext =base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv));
echo $crypttext . "\n";//加密后的内容

echo mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$key,base64_decode($crypttext),MCRYPT_MODE_ECB,$iv);//解密后的内容


在AES加密算法中通常会用到MCRYPT_RIJNDAEL_128、MCRYPT_RIJNDAEL_192、MCRYPT_RIJNDAEL_256三种,后面的128、192、256代表的是秘钥(也就是加密的Key)是多少bit的,比如使用的是MCRYPT_RIJNDAEL_128,那么用这个算法加密时秘钥长度就是128bit的,比如 $key = 'fjjda0&9^$$#+*%$fada',是20个字符,那在实际加密的时候只用到前16个字符加密(16*8=128),不足128bit的php中会用'\0'来补齐。


有的时候做项目对接的时候,可能你用的是Php加密的,而对方用的是java写的,对接的过程中就发现机加密后的内容对方解密不了,这是因为Php跟java在实现这个算法的时候有差别,要想正确加密解密需要两边都做下处理:

PHP:

<?php
class Security {
	public static function encrypt($input, $key) {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = Security::pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = base64_encode($data);
        return $data;
	}
 
	private static function pkcs5_pad ($text, $blocksize) {
		$pad = $blocksize - (strlen($text) % $blocksize);
		return $text . str_repeat(chr($pad), $pad);
	}
 
	public static function decrypt($sStr, $sKey) {
		$decrypted= mcrypt_decrypt(
		MCRYPT_RIJNDAEL_128,
		$sKey,
		base64_decode($sStr),
		MCRYPT_MODE_ECB
	);
 
		$dec_s = strlen($decrypted);
		$padding = ord($decrypted[$dec_s-1]);
		$decrypted = substr($decrypted, 0, -$padding);
		return $decrypted;
	}	
}
 
 
 
$key = "1234567891234567";
$data = "example";
 
$value = Security::encrypt($data , $key );
echo $value.'<br/>';
echo Security::decrypt($value, $key );

Java:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
import org.apache.commons.codec.binary.Base64;
 
public class Security {
	public static String encrypt(String input, String key){
        byte[] crypted = null;
        try{
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        }catch(Exception e){
        System.out.println(e.toString());
	}
	return new String(Base64.encodeBase64(crypted));
}
 
    public static String decrypt(String input, String key){
        byte[] output = null;
        try{
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decodeBase64(input));
            }catch(Exception e){
            System.out.println(e.toString());
        }
        return new String(output);
    }
 
	public static void main(String[] args) {
		String key = "1234567891234567";
		String data = "example";
		
		System.out.println(Security.encrypt(data, key));
		
		System.out.println(Security.decrypt(Security.encrypt(data, key), key));
		
			
	}	
}


2019-10-07 21:05:26 a745233700 阅读数 521
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25413 人正在学习 去看看 邵发

 

一、3DES加密算法简析:

3DES,也称为 3DESede 或 TripleDES,是三重数据加密算法,相当于是对每个数据库应用三次DES的对称加密算法。

由于DES密码长度容易被暴力破解,所以3DES算法通过对DES算法进行改进,增加DES的密钥长度来避免类似的攻击,针对每个数据块进行三次DES加密;因此,3DES加密算法并非什么新的加密算法,是DES的一个更安全的变形,它以DES为基本模块,通过组合分组方法设计出分组加密算法。。

3DES是DES向AES过渡的加密算法,它使用2个或者3个56位的密钥对数据进行三次加密。相比DES,3DES因密钥长度变长,安全性有所提高,但其处理速度不高。因此又出现了AES加密算法,AES较于3DES速度更快、安全性更高。

 

二、3DES加密过程:

该算法的加解密过程分别是对明文/密文数据进行三次DES加密或解密,得到相应的密文或明文。

假设EK()和DK()分别表示DES的加密和解密函数,P表示明文,C表示密文,那么加解密的公式如下:

加密:C = EK3( DK2( EK1(P)) ),即对明文数据进行,加密 --> 解密 --> 加密的过程,最后得到密文数据;

解密:P = DK1( EK2( DK3(C)) ),即对密文数据进行,解密 --> 加密 --> 解密的过程,最后得到明文数据;

其中:K1表示3DES中第一个8字节密钥,K2表示第二个8字节密钥,K3表示第三个8字节密钥,K1、K2、K3决定了算法的安全性,若三个密钥互不相同,本质上就相当于用一个长为168位的密钥进行加密。多年来,它在对付强力攻击时是比较安全的。若数据对安全性要求不那么高,K1可以等于K3。在这种情况下,密钥的有效长度为112位,即K1对应KL(左8字节),K2对应KR(右8字节),K3对应KL(左8字节)。

当三重密钥均相同时,前两步相互抵消,相当于仅实现了一次加密,因此可实现对普通DES加密算法的兼容。

由于DES加解密算法是每8个字节作为一个加解密数据块,因此在实现该算法时,需要对数据进行分块和补位(即最后不足8字节时,要补足8字节)。Java本身提供的API中NoPadding,Zeros填充和PKCS5Padding。假设我们要对9个字节长度的数据进行加密,则其对应的填充说明如下:

(1)NoPadding:API或算法本身不对数据进行处理,加密数据由加密双方约定填补算法。例如若对字符串数据进行加解密,可以补充\0或者空格,然后trim;

(2)ZerosPadding:无数据的字节全部被填充为0;

第一块:F0 F1 F2 F3 F4 F5 F6 F7

第二块:F8 0 0 0 0 0 0 0

(3)PKCS5Padding:每个被填充的字节都记录了被填充的长度;

①加密前:数据字节长度对8取余,余数为m,若m>0,则补足8-m个字节,字节数值为8-m,即差几个字节就补几个字节,字节数值即为补充的字节数,若为0则补充8个字节的8。

②解密后:取最后一个字节,值为m,则从数据尾部删除m个字节,剩余数据即为加密前的原文。

③加密字符串为为AAA,则补位为AAA55555;加密字符串为BBBBBB,则补位为BBBBBB22;加密字符串为CCCCCCCC,则补位为CCCCCCCC88888888。

(4)PKCS7Padding:

PKCS7Padding 的填充方式和PKCS5Padding 填充方式一样。只是加密块的字节数不同。PKCS5Padding明确定义了加密块是8字节,PKCS7Padding加密快可以是1-255之间。

 

三、3DES解密:

3DES解密过程,与加密过程相反,即逆序使用密钥。是以密钥3、密钥2、密钥1的顺序执行 解密->加密->解密

 

 

四、Java使用3DES加密解密的流程:

3des加密解密详细解释

  ①传入共同约定的密钥(keyBytes)以及算法(Algorithm),来构建SecretKey密钥对象:

  SecretKey deskey = new SecretKeySpec(keyBytes, Algorithm);

  ②根据算法实例化Cipher对象,它负责加密/解密:

  Cipher c1 = Cipher.getInstance(Algorithm);

  ③传入加密/解密模式以及SecretKey密钥对象,实例化Cipher对象:

  c1.init(Cipher.ENCRYPT_MODE, deskey);

  ④传入字节数组,调用Cipher.doFinal()方法,实现加密/解密,并返回一个byte字节数组:

  c1.doFinal(src);

Java语言加密案例:

/*字符串 DESede(3DES) 加密*/
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
public class Des3 {
 
    private static final String Algorithm = "DESede"; // 定义 加密算法,可用DES,DESede,Blowfish

    // 加密函数
    // keybyte为加密密钥,长度为24字节
    // src为被加密的数据缓冲区(源)
    public static byte[] encryptMode(byte[] keybyte, byte[] src) {
        try {
            // 生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            // 加密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.ENCRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }
 
    // 解密函数
    // keybyte为加密密钥,长度为24字节
    // src为加密后的缓冲区
    public static byte[] decryptMode(byte[] keybyte, byte[] src) {
        try {
            // 生成密钥
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
            // 解密
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(Cipher.DECRYPT_MODE, deskey);
            return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        return null;
    }
 
    // 转换成十六进制字符串
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
            if (n < b.length - 1) {
                hs = hs + ":";
            }
        }
        return hs.toUpperCase();
    }
 
    public static void main(String[] args) {
 
        // 添加新安全算法,如果用JCE就要把它添加进去
        Security.addProvider(new com.sun.crypto.provider.SunJCE());
        final byte[] keyBytes = { 0x11, 0x22, 0x4F, 0x58, (byte) 0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51, (byte) 0xCB, (byte) 0xDD, 0x55, 0x66, 0x77, 0x29, 0x74, (byte) 0x98, 0x30, 0x40, 0x36, (byte) 0xE2 }; // 24字节的密钥
 
        String szSrc = "This is a 3DES test. 测试";
        System.out.println("加密前的字符串:" + szSrc);
 
        byte[] encoded = encryptMode(keyBytes, szSrc.getBytes());
        System.out.println("加密后的字符串:" + new String(encoded));
 
        byte[] srcBytes = decryptMode(keyBytes, encoded);
        System.out.println("解密后的字符串:" + (new String(srcBytes)));
    }
}

 

 

2015-06-26 17:50:19 5iasp 阅读数 5480
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25413 人正在学习 去看看 邵发

代码如下:

package com.yanek.util;


import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

/**
 * 运算模式CBC。<br>
 * 在CBC模式下使用key,向量iv;<br>
 * 对字符加密时,双方采用的都是UTF-8编码
 * @version 1.0.0
 */
public class DesUtil {

	// 向量
	private static final byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };

	/**
	 * CBC解密
	 * 
	 * @param key
	 *            密钥
	 * @param data
	 *            Base64编码的密文
	 * @return 明文
	 * @throws Exception
	 */
	public static byte[] desDecodeCBC(byte[] key, byte[] data) throws Exception {
		Key deskey = null;
		DESKeySpec spec = new DESKeySpec(key);
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DES");
		deskey = keyfactory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		IvParameterSpec ips = new IvParameterSpec(keyiv);
		cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
		byte[] bOut = cipher.doFinal(data);
		return bOut;
	}

	/**
	 * CBC解密
	 * 
	 * @param key
	 *            密钥
	 * @param data
	 *            Base64加密后的密文
	 * @return 明文
	 * @throws Exception
	 */
	public static String desDecodeCBC(String key, String data) throws Exception {
		byte[] _data = Base64.decodeBase64(data);
		byte[] _key = key.getBytes("UTF-8");
		byte[] bOut = desDecodeCBC(_key, _data);

		return new String(bOut, "UTF-8");
	}

	/**
	 * CBC加密
	 * 
	 * @param key
	 *            密钥
	 * @param data
	 *            明文
	 * @return 密文
	 * @throws Exception
	 */
	public static byte[] desEncodeCBC(byte[] key, byte[] data) throws Exception {
		Key deskey = null;
		DESKeySpec spec = new DESKeySpec(key);
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DES");
		deskey = keyfactory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding"); // 加密方法/运算模式/填充模式
		IvParameterSpec ips = new IvParameterSpec(keyiv);
		cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
		byte[] bOut = cipher.doFinal(data);
		return bOut;
	}

	/**
	 * CBC加密
	 * 
	 * @param key
	 *            密钥
	 * @param data
	 *            明文
	 * @return Base64加密后的密文
	 * @throws Exception
	 */
	public static String desEncodeCBC(String key, String data) throws Exception {
		byte[] _data = data.getBytes("UTF-8");
		byte[] _key = key.getBytes("UTF-8");
		byte[] bOut = desEncodeCBC(_key, _data);

		return Base64.encodeBase64String(bOut); // Base64加密后的密文
	}

	public static void main(String[] args) throws Exception {

		String key = "hdhhdhdmZtmcOlmT2";
		String data = "学习测试";

		System.out.println("加密解密 测试 ");
		String str1 = desEncodeCBC(key, data);// 加密
		String str2 = desDecodeCBC(key, str1);// 解密
		System.out.println(str1);
		System.out.println(str2);

	}
}


 

2019-09-20 14:32:49 BingHongChaZuoAn 阅读数 241
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25413 人正在学习 去看看 邵发

  今天介绍下对称加密的3DES加密。

3des加密是比较安全的对称加密算法,是3层des加密后的算法。

双方约定好相同的key,以及偏移量iv,加密模式,填充,然后进行加解密。

只有4个变量都相同才能加解密一致,所以安全上来说是比较安全的。

1.加密模式包含:

EBC、CBC、CTR、OFB、CFB

2.填充包含:

pcks5padding、pcks7padding 、zeropadding、iso10126、ansix923

3 key和iv  双方约定就好了。

以下是js的3des加密:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>3des加解密</title>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" src="3DES.js"></script>
</head>
<body>
<script type="text/javascript">
var str = "15629551180";
document.write("原字符串:</br>"+str);
var key = "sdghjsdhgjhsdkjghioewiouew234231";         
//alert(decrypt_3des);
var des3en = DES3.encrypt(key,str);
document.write("</br>des3加密后:</br>"+des3en);
document.write("</br>des3解密后:</br>"+DES3.decrypt(key,des3en));
</script>
</body>

3DES.js

/** 
 * DES 加密算法 
 * 
 * 该函数接受一个 8 字节字符串作为普通 DES 算法的密钥(也就是 64 位,但是算法只使用 56 位),或者接受一个 24 字节字符串作为 3DES 
 * 算法的密钥;第二个参数是要加密或解密的信息字符串;第三个布尔值参数用来说明信息是加密还是解密;接下来的可选参数 mode 如果是 0 表示 ECB 
 * 模式,1 表示 CBC 模式,默认是 ECB 模式;最后一个可选项是一个 8 字节的输入向量字符串(在 ECB 模式下不使用)。返回的密文是字符串。 
 * 
 * 参数: <br> 
 * key: 8字节字符串作为普通 DES 算法的密钥,或 24 字节字符串作为 3DES <br> 
 * message: 加密或解密的信息字符串<br> 
 * encrypt: 布尔值参数用来说明信息是加密还是解密<br> 
 * mode: 1:CBC模式,0:ECB模式(默认)<br> 
 * iv:<br> 
 * padding: 可选项, 8字节的输入向量字符串(在 ECB 模式下不使用) 
 */
//this takes the key, the message, and whether to encrypt or decrypt
function des (key, message, encrypt, mode, iv, padding) {
  if(encrypt) //如果是加密的话,首先转换编码
    message = unescape(encodeURIComponent(message));
  //declaring this locally speeds things up a bit
  var spfunction1 = new Array (0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004);
  var spfunction2 = new Array (-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000);
  var spfunction3 = new Array (0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200);
  var spfunction4 = new Array (0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080);
  var spfunction5 = new Array (0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100);
  var spfunction6 = new Array (0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010);
  var spfunction7 = new Array (0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002);
  var spfunction8 = new Array (0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000);
  //create the 16 or 48 subkeys we will need
  var keys = des_createKeys (key);
  var m=0, i, j, temp, temp2, right1, right2, left, right, looping;
  var cbcleft, cbcleft2, cbcright, cbcright2
  var endloop, loopinc;
  var len = message.length;
  var chunk = 0;
  //set up the loops for single and triple des
  var iterations = keys.length == 32 ? 3 : 9; //single or triple des
  if (iterations == 3) {looping = encrypt ? new Array (0, 32, 2) : new Array (30, -2, -2);}
  else {looping = encrypt ? new Array (0, 32, 2, 62, 30, -2, 64, 96, 2) : new Array (94, 62, -2, 32, 64, 2, 30, -2, -2);}
  //pad the message depending on the padding parameter
  if (padding == 2) message += "    "; //pad the message with spaces
  else if (padding == 1) {
    if(encrypt) {
      temp = 8-(len%8);
      message += String.fromCharCode(temp,temp,temp,temp,temp,temp,temp,temp);
      if (temp===8) len+=8;
    }
  } //PKCS7 padding
  else if (!padding) message += "\0\0\0\0\0\0\0\0"; //pad the message out with null bytes
  //store the result here
  var result = "";
  var tempresult = "";
  if (mode == 1) { //CBC mode
    cbcleft = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);
    cbcright = (iv.charCodeAt(m++) << 24) | (iv.charCodeAt(m++) << 16) | (iv.charCodeAt(m++) << 8) | iv.charCodeAt(m++);
    m=0;
  }
  //loop through each 64 bit chunk of the message
  while (m < len) {
    left = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);
    right = (message.charCodeAt(m++) << 24) | (message.charCodeAt(m++) << 16) | (message.charCodeAt(m++) << 8) | message.charCodeAt(m++);
    //for Cipher Block Chaining mode, xor the message with the previous result
    if (mode == 1) {if (encrypt) {left ^= cbcleft; right ^= cbcright;} else {cbcleft2 = cbcleft; cbcright2 = cbcright; cbcleft = left; cbcright = right;}}
    //first each 64 but chunk of the message must be permuted according to IP
    temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
    temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);
    temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);
    temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
    left = ((left << 1) | (left >>> 31));
    right = ((right << 1) | (right >>> 31));
    //do this either 1 or 3 times for each chunk of the message
    for (j=0; j<iterations; j+=3) {
      endloop = looping[j+1];
      loopinc = looping[j+2];
      //now go through and perform the encryption or decryption
      for (i=looping[j]; i!=endloop; i+=loopinc) { //for efficiency
        right1 = right ^ keys[i];
        right2 = ((right >>> 4) | (right << 28)) ^ keys[i+1];
        //the result is attained by passing these bytes through the S selection functions
        temp = left;
        left = right;
        right = temp ^ (spfunction2[(right1 >>> 24) & 0x3f] | spfunction4[(right1 >>> 16) & 0x3f]
          | spfunction6[(right1 >>> 8) & 0x3f] | spfunction8[right1 & 0x3f]
          | spfunction1[(right2 >>> 24) & 0x3f] | spfunction3[(right2 >>> 16) & 0x3f]
          | spfunction5[(right2 >>> 8) & 0x3f] | spfunction7[right2 & 0x3f]);
      }
      temp = left; left = right; right = temp; //unreverse left and right
    } //for either 1 or 3 iterations
    //move then each one bit to the right
    left = ((left >>> 1) | (left << 31));
    right = ((right >>> 1) | (right << 31));
    //now perform IP-1, which is IP in the opposite direction
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
    temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
    temp = ((right >>> 2) ^ left) & 0x33333333; left ^= temp; right ^= (temp << 2);
    temp = ((left >>> 16) ^ right) & 0x0000ffff; right ^= temp; left ^= (temp << 16);
    temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
    //for Cipher Block Chaining mode, xor the message with the previous result
    if (mode == 1) {if (encrypt) {cbcleft = left; cbcright = right;} else {left ^= cbcleft2; right ^= cbcright2;}}
    tempresult += String.fromCharCode ((left>>>24), ((left>>>16) & 0xff), ((left>>>8) & 0xff), (left & 0xff), (right>>>24), ((right>>>16) & 0xff), ((right>>>8) & 0xff), (right & 0xff));
    chunk += 8;
    if (chunk == 512) {result += tempresult; tempresult = ""; chunk = 0;}
  } //for every 8 characters, or 64 bits in the message
  //return the result as an array
  result += tempresult;
  result = result.replace(/\0*$/g, "");
  if(!encrypt ) { //如果是解密的话,解密结束后对PKCS7 padding进行解码,并转换成utf-8编码
    if(padding === 1) { //PKCS7 padding解码
      var len = result.length, paddingChars = 0;
      len && (paddingChars = result.charCodeAt(len-1));
      (paddingChars <= 8) && (result = result.substring(0, len - paddingChars));
    }
    //转换成UTF-8编码
    result = decodeURIComponent(escape(result));
  }
  return result;
} //end of des
//des_createKeys
//this takes as input a 64 bit key (even though only 56 bits are used)
//as an array of 2 integers, and returns 16 48 bit keys
function des_createKeys (key) {
  //declaring this locally speeds things up a bit
  var pc2bytes0 = new Array (0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204);
  var pc2bytes1 = new Array (0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101);
  var pc2bytes2 = new Array (0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808);
  var pc2bytes3 = new Array (0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000);
  var pc2bytes4 = new Array (0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010);
  var pc2bytes5 = new Array (0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420);
  var pc2bytes6 = new Array (0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002);
  var pc2bytes7 = new Array (0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800);
  var pc2bytes8 = new Array (0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002);
  var pc2bytes9 = new Array (0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408);
  var pc2bytes10 = new Array (0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020);
  var pc2bytes11 = new Array (0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200);
  var pc2bytes12 = new Array (0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010);
  var pc2bytes13 = new Array (0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105);
  //how many iterations (1 for des, 3 for triple des)
  var iterations = key.length > 8 ? 3 : 1; //changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys
  //stores the return keys
  var keys = new Array (32 * iterations);
  //now define the left shifts which need to be done
  var shifts = new Array (0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0);
  //other variables
  var lefttemp, righttemp, m=0, n=0, temp;
  for (var j=0; j<iterations; j++) { //either 1 or 3 iterations
    var left = (key.charCodeAt(m++) << 24) | (key.charCodeAt(m++) << 16) | (key.charCodeAt(m++) << 8) | key.charCodeAt(m++);
    var right = (key.charCodeAt(m++) << 24) | (key.charCodeAt(m++) << 16) | (key.charCodeAt(m++) << 8) | key.charCodeAt(m++);
    temp = ((left >>> 4) ^ right) & 0x0f0f0f0f; right ^= temp; left ^= (temp << 4);
    temp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= temp; right ^= (temp << -16);
    temp = ((left >>> 2) ^ right) & 0x33333333; right ^= temp; left ^= (temp << 2);
    temp = ((right >>> -16) ^ left) & 0x0000ffff; left ^= temp; right ^= (temp << -16);
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
    temp = ((right >>> 8) ^ left) & 0x00ff00ff; left ^= temp; right ^= (temp << 8);
    temp = ((left >>> 1) ^ right) & 0x55555555; right ^= temp; left ^= (temp << 1);
    //the right side needs to be shifted and to get the last four bits of the left side
    temp = (left << 8) | ((right >>> 20) & 0x000000f0);
    //left needs to be put upside down
    left = (right << 24) | ((right << 8) & 0xff0000) | ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0);
    right = temp;
    //now go through and perform these shifts on the left and right keys
    for (var i=0; i < shifts.length; i++) {
      //shift the keys either one or two bits to the left
      if (shifts[i]) {left = (left << 2) | (left >>> 26); right = (right << 2) | (right >>> 26);}
      else {left = (left << 1) | (left >>> 27); right = (right << 1) | (right >>> 27);}
      left &= -0xf; right &= -0xf;
      //now apply PC-2, in such a way that E is easier when encrypting or decrypting
      //this conversion will look like PC-2 except only the last 6 bits of each byte are used
      //rather than 48 consecutive bits and the order of lines will be according to
      //how the S selection functions will be applied: S2, S4, S6, S8, S1, S3, S5, S7
      lefttemp = pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf]
        | pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf]
        | pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf]
        | pc2bytes6[(left >>> 4) & 0xf];
      righttemp = pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf]
        | pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf]
        | pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf]
        | pc2bytes13[(right >>> 4) & 0xf];
      temp = ((righttemp >>> 16) ^ lefttemp) & 0x0000ffff;
      keys[n++] = lefttemp ^ temp; keys[n++] = righttemp ^ (temp << 16);
    }
  } //for each iterations
  //return the keys we've created
  return keys;
} //end of des_createKeys
function genkey(key, start, end) {
  //8 byte / 64 bit Key (DES) or 192 bit Key
  return {key:pad(key.slice(start, end)),vector: 1};
}
function pad(key) {
  for (var i = key.length; i<24; i++) {
    key+="0";
  }
  return key;
}
var des3iv = '12345678';
var DES3 = {
  //3DES加密,CBC/PKCS5Padding
  encrypt:function(key,input){
    var genKey = genkey(key, 0, 24);
    return btoa(des(genKey.key, input, 1, 1, des3iv, 1));
  },
  ////3DES解密,CBC/PKCS5Padding
  decrypt:function(key,input){
    var genKey = genkey(key, 0, 24); 
    return des(genKey.key, atob(input), 0, 1, des3iv, 1); 
  }
};

 

DES加密工具类

阅读数 228

Des加密

阅读数 78

DES加密

阅读数 61

python实现des加密

阅读数 2699

没有更多推荐了,返回首页