Java加密技术(二)

关键字: des, desede, aes, blowfish, rc2, rc4, arcfour, tripledes, 3de, 对称加密

    接下来我们介绍对称加密算法,最常用的莫过于DES数据加密算法。
DES
DES-Data Encryption Standard,即数据加密算法。是IBM公司于1975年研究成功并公开发表的。DES算法的入口参数有三个:Key、Data、Mode。其中Key为8个字节共64位,是DES算法的工作密钥;Data也为8个字节64位,是要被加密或被解密的数据;Mode为DES的工作方式,有两种:加密或解密。
  DES算法把64位的明文输入块变为64位的密文输出块,它所使用的密钥也是64位。



通过java代码实现如下: Coder类见 Java加密技术(一)
Java代码 复制代码
  1. import java.security.Key;   
  2. import java.security.SecureRandom;   
  3.   
  4. import javax.crypto.Cipher;   
  5. import javax.crypto.KeyGenerator;   
  6. import javax.crypto.SecretKey;   
  7. import javax.crypto.SecretKeyFactory;   
  8. import javax.crypto.spec.DESKeySpec;   
  9.   
  10.   
  11. /**  
  12.  * DES安全编码组件  
  13.  *   
  14.  * <pre>  
  15.  * 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)  
  16.  * DES                  key size must be equal to 56  
  17.  * DESede(TripleDES)    key size must be equal to 112 or 168  
  18.  * AES                  key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available  
  19.  * Blowfish             key size must be multiple of 8, and can only range from 32 to 448 (inclusive)  
  20.  * RC2                  key size must be between 40 and 1024 bits  
  21.  * RC4(ARCFOUR)         key size must be between 40 and 1024 bits  
  22.  * 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html  
  23.  * </pre>  
  24.  *   
  25.  * @author 梁栋  
  26.  * @version 1.0  
  27.  * @since 1.0  
  28.  */  
  29. public abstract class DESCoder extends Coder {   
  30.     /**  
  31.      * ALGORITHM 算法 <br>  
  32.      * 可替换为以下任意一种算法,同时key值的size相应改变。  
  33.      *   
  34.      * <pre>  
  35.      * DES                  key size must be equal to 56  
  36.      * DESede(TripleDES)    key size must be equal to 112 or 168  
  37.      * AES                  key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available  
  38.      * Blowfish             key size must be multiple of 8, and can only range from 32 to 448 (inclusive)  
  39.      * RC2                  key size must be between 40 and 1024 bits  
  40.      * RC4(ARCFOUR)         key size must be between 40 and 1024 bits  
  41.      * </pre>  
  42.      *   
  43.      * 在Key toKey(byte[] key)方法中使用下述代码  
  44.      * <code>SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);</code> 替换  
  45.      * <code>  
  46.      * DESKeySpec dks = new DESKeySpec(key);  
  47.      * SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);  
  48.      * SecretKey secretKey = keyFactory.generateSecret(dks);  
  49.      * </code>  
  50.      */  
  51.     public static final String ALGORITHM = "DES";   
  52.   
  53.     /**  
  54.      * 转换密钥<br>  
  55.      *   
  56.      * @param key  
  57.      * @return  
  58.      * @throws Exception  
  59.      */  
  60.     private static Key toKey(byte[] key) throws Exception {   
  61.         DESKeySpec dks = new DESKeySpec(key);   
  62.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);   
  63.         SecretKey secretKey = keyFactory.generateSecret(dks);   
  64.   
  65.         // 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码   
  66.         // SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);   
  67.   
  68.         return secretKey;   
  69.     }   
  70.   
  71.     /**  
  72.      * 解密  
  73.      *   
  74.      * @param data  
  75.      * @param key  
  76.      * @return  
  77.      * @throws Exception  
  78.      */  
  79.     public static byte[] decrypt(byte[] data, String key) throws Exception {   
  80.         Key k = toKey(decryptBASE64(key));   
  81.   
  82.         Cipher cipher = Cipher.getInstance(ALGORITHM);   
  83.         cipher.init(Cipher.DECRYPT_MODE, k);   
  84.   
  85.         return cipher.doFinal(data);   
  86.     }   
  87.   
  88.     /**  
  89.      * 加密  
  90.      *   
  91.      * @param data  
  92.      * @param key  
  93.      * @return  
  94.      * @throws Exception  
  95.      */  
  96.     public static byte[] encrypt(byte[] data, String key) throws Exception {   
  97.         Key k = toKey(decryptBASE64(key));   
  98.         Cipher cipher = Cipher.getInstance(ALGORITHM);   
  99.         cipher.init(Cipher.ENCRYPT_MODE, k);   
  100.   
  101.         return cipher.doFinal(data);   
  102.     }   
  103.   
  104.     /**  
  105.      * 生成密钥  
  106.      *   
  107.      * @return  
  108.      * @throws Exception  
  109.      */  
  110.     public static String initKey() throws Exception {   
  111.         return initKey(null);   
  112.     }   
  113.   
  114.     /**  
  115.      * 生成密钥  
  116.      *   
  117.      * @param seed  
  118.      * @return  
  119.      * @throws Exception  
  120.      */  
  121.     public static String initKey(String seed) throws Exception {   
  122.         SecureRandom secureRandom = null;   
  123.   
  124.         if (seed != null) {   
  125.             secureRandom = new SecureRandom(decryptBASE64(seed));   
  126.         } else {   
  127.             secureRandom = new SecureRandom();   
  128.         }   
  129.   
  130.         KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);   
  131.         kg.init(secureRandom);   
  132.   
  133.         SecretKey secretKey = kg.generateKey();   
  134.   
  135.         return encryptBASE64(secretKey.getEncoded());   
  136.     }   
  137. }  
import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


/**
 * DES安全编码组件
 * 
 * <pre>
 * 支持 DES、DESede(TripleDES,就是3DES)、AES、Blowfish、RC2、RC4(ARCFOUR)
 * DES          		key size must be equal to 56
 * DESede(TripleDES) 	key size must be equal to 112 or 168
 * AES          		key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
 * Blowfish     		key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
 * RC2          		key size must be between 40 and 1024 bits
 * RC4(ARCFOUR) 		key size must be between 40 and 1024 bits
 * 具体内容 需要关注 JDK Document http://.../docs/technotes/guides/security/SunProviders.html
 * </pre>
 * 
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public abstract class DESCoder extends Coder {
	/**
	 * ALGORITHM 算法 <br>
	 * 可替换为以下任意一种算法,同时key值的size相应改变。
	 * 
	 * <pre>
	 * DES          		key size must be equal to 56
	 * DESede(TripleDES) 	key size must be equal to 112 or 168
	 * AES          		key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
	 * Blowfish     		key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
	 * RC2          		key size must be between 40 and 1024 bits
	 * RC4(ARCFOUR) 		key size must be between 40 and 1024 bits
	 * </pre>
	 * 
	 * 在Key toKey(byte[] key)方法中使用下述代码
	 * <code>SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);</code> 替换
	 * <code>
	 * DESKeySpec dks = new DESKeySpec(key);
	 * SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
	 * SecretKey secretKey = keyFactory.generateSecret(dks);
	 * </code>
	 */
	public static final String ALGORITHM = "DES";

	/**
	 * 转换密钥<br>
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	private static Key toKey(byte[] key) throws Exception {
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
		SecretKey secretKey = keyFactory.generateSecret(dks);

		// 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
		// SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);

		return secretKey;
	}

	/**
	 * 解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] data, String key) throws Exception {
		Key k = toKey(decryptBASE64(key));

		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, k);

		return cipher.doFinal(data);
	}

	/**
	 * 加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] data, String key) throws Exception {
		Key k = toKey(decryptBASE64(key));
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, k);

		return cipher.doFinal(data);
	}

	/**
	 * 生成密钥
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String initKey() throws Exception {
		return initKey(null);
	}

	/**
	 * 生成密钥
	 * 
	 * @param seed
	 * @return
	 * @throws Exception
	 */
	public static String initKey(String seed) throws Exception {
		SecureRandom secureRandom = null;

		if (seed != null) {
			secureRandom = new SecureRandom(decryptBASE64(seed));
		} else {
			secureRandom = new SecureRandom();
		}

		KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
		kg.init(secureRandom);

		SecretKey secretKey = kg.generateKey();

		return encryptBASE64(secretKey.getEncoded());
	}
}

延续上一个类的实现,我们通过MD5以及SHA对字符串加密生成密钥,这是比较常见的密钥生成方式。
再给出一个测试类:
Java代码 复制代码
  1. import static org.junit.Assert.*;   
  2.   
  3. import org.junit.Test;   
  4.   
  5. /**  
  6.  *   
  7.  * @author 梁栋  
  8.  * @version 1.0  
  9.  * @since 1.0  
  10.  */  
  11. public class DESCoderTest {   
  12.   
  13.     @Test  
  14.     public void test() throws Exception {   
  15.         String inputStr = "DES";   
  16.         String key = DESCoder.initKey();   
  17.         System.err.println("原文:/t" + inputStr);   
  18.   
  19.         System.err.println("密钥:/t" + key);   
  20.   
  21.         byte[] inputData = inputStr.getBytes();   
  22.         inputData = DESCoder.encrypt(inputData, key);   
  23.   
  24.         System.err.println("加密后:/t" + DESCoder.encryptBASE64(inputData));   
  25.   
  26.         byte[] outputData = DESCoder.decrypt(inputData, key);   
  27.         String outputStr = new String(outputData);   
  28.   
  29.         System.err.println("解密后:/t" + outputStr);   
  30.   
  31.         assertEquals(inputStr, outputStr);   
  32.     }   
  33. }  
import static org.junit.Assert.*;

import org.junit.Test;

/**
 * 
 * @author 梁栋
 * @version 1.0
 * @since 1.0
 */
public class DESCoderTest {

	@Test
	public void test() throws Exception {
		String inputStr = "DES";
		String key = DESCoder.initKey();
		System.err.println("原文:/t" + inputStr);

		System.err.println("密钥:/t" + key);

		byte[] inputData = inputStr.getBytes();
		inputData = DESCoder.encrypt(inputData, key);

		System.err.println("加密后:/t" + DESCoder.encryptBASE64(inputData));

		byte[] outputData = DESCoder.decrypt(inputData, key);
		String outputStr = new String(outputData);

		System.err.println("解密后:/t" + outputStr);

		assertEquals(inputStr, outputStr);
	}
}

得到的输出内容如下:
Console代码 复制代码
  1. 原文: DES   
  2. 密钥: f3wEtRrV6q0=   
  3.   
  4. 加密后:    C6qe9oNIzRY=   
  5.   
  6. 解密后:    DES  

    由控制台得到的输出,我们能够比对加密、解密后结果一致。这是一种简单的加密解密方式,只有一个密钥。
    其实DES有很多同胞兄弟,如DESede(TripleDES)、AES、Blowfish、RC2、RC4(ARCFOUR)。这里就不过多阐述了,大同小异,只要换掉ALGORITHM换成对应的值,同时做一个代码替换 SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);就可以了,此外就是密钥长度不同了。

Java代码 复制代码
  1. /**  
  2.  * DES          key size must be equal to 56  
  3.  * DESede(TripleDES) key size must be equal to 112 or 168  
  4.  * AES          key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available  
  5.  * Blowfish     key size must be multiple of 8, and can only range from 32 to 448 (inclusive)  
  6.  * RC2          key size must be between 40 and 1024 bits  
  7.  * RC4(ARCFOUR) key size must be between 40 and 1024 bits  
  8.  **/  
/**
 * DES          key size must be equal to 56
 * DESede(TripleDES) key size must be equal to 112 or 168
 * AES          key size must be equal to 128, 192 or 256,but 192 and 256 bits may not be available
 * Blowfish     key size must be multiple of 8, and can only range from 32 to 448 (inclusive)
 * RC2          key size must be between 40 and 1024 bits
 * RC4(ARCFOUR) key size must be between 40 and 1024 bits
 **/


相关链接:
Java加密技术(一)
Java加密技术(二)
Java加密技术(三)
Java加密技术(四)
Java加密技术(五)
Java加密技术(六)
Java加密技术(七)
Java加密技术(八)
Java加密技术(九)
Java加密技术(十)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
数据加密技术 我们经常需要一种措施来保护我们的数据,防止被一些怀有不良用心的人所看到或者破坏。在信息时代,信息可以帮助团体或个人,使他们受益,同样,信息也可以用来对他们构成威胁,造成破坏。在竞争激烈的大公司中,工业间谍经常会获取对方的情报。因此,在客观上就需要一种强有力的安全措施来保护机密数据不被窃取或篡改。数据加密与解密从宏观上讲是非常简单的,很容易理解。加密与解密的一些方法是非常直接的,很容易掌握,可以很方便的对机密数据进行加密和解密。 一:数据加密方法 在传统上,我们有几种方法来加密数据流。所有这些方法都可以用软件很容易的实现,但是当我们只知道密文的时候,是不容易破译这些加密算法的(当同时有原文和密文时,破译加密算法虽然也不是很容易,但已经是可能的了)。最好的加密算法对系统性能几乎没有影响,并且还可以带来其他内在的优点。例如,大家都知道的pkzip,它既压缩数据又加密数据。又如,dbms的一些软件包总是包含一些加密方法以使复制文件这一功能对一些敏感数据是无效的,或者需要用户的密码。所有这些加密算法都要有高效的加密和解密能力。 幸运的是,在所有的加密算法中最简单的一种就是“置换表”算法,这种算法也能很好达到加密的需要。每一个数据段(总是一个字节)对应着“置换表”中的一个偏移量,偏移量所对应的值就输出成为加密后的文件。加密程序和解密程序都需要一个这样的“置换表”。事实上,80x86 cpu系列就有一个指令‘xlat’在硬件级来完成这样的工作。这种加密算法比较简单,加密解密速度都很快,但是一旦这个“置换表”被对方获得,那这个加密方案就完全被识破了。更进一步讲,这种加密算法对于黑客破译来讲是相当直接的,只要找到一个“置换表”就可以了。这种方法在计算机出现之前就已经被广泛的使用。 对这种“置换表”方式的一个改进就是使用2个或者更多的“置换表”,这些表都是基于数据流中字节的位置的,或者基于数据流本身。这时,破译变的更加困难,因为黑客必须正确的做几次变换。通过使用更多的“置换表”,并且按伪随机的方式使用每个表,这种改进的加密方法已经变的很难破译。比如,我们可以对所有的偶数位置的数据使用a表,对所有的奇数位置使用b表,即使黑客获得了明文和密文,他想破译这个加密方案也是非常困难的,除非黑客确切的知道用了两张表。 与使用“置换表”相类似,“变换数据位置”也在计算机加密中使用。但是,这需要更多的执行时间。从输入中读入明文放到一个buffer中,再在buffer中对他们重排序,然后按这个顺序再输出。解密程序按相反的顺序还原数据。这种方法总是和一些别的加密算法混合使用,这就使得破译变的特别的困难,几乎有些不可能了。例如,有这样一个词,变换起字母的顺序,slient 可以变为listen,但所有的字母都没有变化,没有增加也没有减少,但是字母之间的顺序已经变化了。 但是,还有一种更好的加密算法,只有计算机可以做,就是字/字节循环移位和xor操作。如果我们把一个字或字节在一个数据流内做循环移位,使用多个或变化的方向(左移或右移),就可以迅速的产生一个加密的数据流。这种方法是很好的,破译它就更加困难!而且,更进一步的是,如果再使用xor操作,按位做异或操作,就就使破译密码更加困难了。如果再使用伪随机的方法,这涉及到要产生一系列的数字,我们可以使用fibbonaci数列。对数列所产生的数做模运算(例如模3),得到一个结果,然后循环移位这个结果的次数,将使破译次密码变的几乎不可能!但是,使用fibbonaci数列这种伪随机的方式所产生的密码对我们的解密程序来讲是非常容易的。 在一些情况下,我们想能够知道数据是否已经被篡改了或被破坏了,这时就需要产生一些校验码,并且把这些校验码插入到数据流中。这样做对数据的防伪与程序本身都是有好处的。但是感染计算机程序的病毒才不会在意这些数据或程序是否加过密,是否有数字签名。所以,加密程序在每次load到内存要开始执行时,都要检查一下本身是否被病毒感染,对与需要加、解密的文件都要做这种检查!很自然,这样一种方法体制应该保密的,因为病毒程序的编写者将会利用这些来破坏别人的程序或数据。因此,在一些反病毒或杀病毒软件中一定要使用加密技术。 循环冗余校验是一种典型的校验数据的方法。对于每一个数据块,它使用位循环移位和xor操作来产生一个16位或32位的校验和 ,这使得丢失一位或两个位的错误一定会导致校验和出错。这种方式很久以来就应用于文件的传输,例如 xmodem-crc。 这是方法已经成为标准,而且有详细的文档。但是,基于标准crc算法的一种修改算法对于发现加密数据块中的错误和文件是否被病毒感染是很有效的。 二.基于公钥

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值