Java加密技术(二)
时间:2010-12-12
接下来我们介绍对称加密算法,最常用的莫过于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加密技术(二)(2)
时间:2010-12-12
Java代码
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
|