|
package com.lain.crypto;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* 加密工具类
******************************************************
* @author linfan
* @date 2006-10-20
* @time 18:12:24
* @project wbe
* @package com.lain.crypto
* @file Cryptor.java
* @type Cryptor
******************************************************
*/
public class Cryptor {
//加密算法名称
public final static String AES = "AES";
public final static String Blowfish = "Blowfish";
public final static String DES = "DES";
public final static String DESede = "DESede";
public final static String RC2 = "RC2";
private KeyGenerator keygen; //KEY 产生器
private Cipher cipher; //加解密器
private String type = Blowfish; //加密类型
public Cryptor(){
}
public Cryptor(String type){
this.type = type;
}
public KeyGenerator getKeyGen() throws Exception{
if(keygen == null){
keygen = KeyGenerator.getInstance(getType());
}
return keygen;
}
public Cipher getCipher() throws Exception{
if(cipher == null){
cipher = Cipher.getInstance(getType());
}
return cipher;
}
public SecretKey getSecretKey() throws Exception{
return getKeyGen().generateKey();
}
public SecretKey getSecretKey(byte[] encode){
return new SecretKeySpec(encode, getType());
}
/**
* 加密
* @param enKey
* @param data
* @return 加密后的数据
* @throws Exception
* @return byte[]
*/
public byte[] enCrypto(SecretKey key ,byte[] data) throws Exception{
Cipher enCipher = getCipher();
enCipher.init(Cipher.ENCRYPT_MODE, key);
return enCipher.doFinal(data);
}
/**
* 解密
* @param deKey
* @param data
* @return 解密后的数据
* @throws Exception
* @return byte[]
*/
public byte[] deCrypto(SecretKey key , byte[] data) throws Exception{
Cipher enCipher = getCipher();
enCipher.init(Cipher.DECRYPT_MODE, key);
return enCipher.doFinal(data);
}
/**
* 获得加密类型
* @return TYPE
* @return String
*/
public String getType() {
return type;
}
/**
* 设置加密类型
* @param type
* @return void
*/
public void setType(String type) {
this.type = type;
}
/**
* 测试试法
* @param args
* @throws Exception
* @return void
*/
public static void main(String[] args) throws Exception {
String source = "lain fan"; //加密前的数据
System.out.println("source :"+source);
//开始加密---->
byte[] src = source.getBytes();
Cryptor cryptor = new Cryptor();
cryptor.setType(Cryptor.Blowfish );
SecretKey key = cryptor.getSecretKey(new byte[]{0,1,2,3,4,5});
//SecretKey key = cryptor.getSecretKey();
byte[] en = cryptor.enCrypto(key,src);
//加密完毕<-----
//显示加密后的内容
StringBuffer buff = new StringBuffer();
for (int i = 0; i < en.length ; i++) {
buff.append(String.valueOf(en + " "));
}
System.out.println("enCrypto :"+String.valueOf(buff.toString()));
//开始解密---->
byte[] de = cryptor.deCrypto(key,en);
//解密完毕<----
//显示解密后的内容
buff = new StringBuffer();
for (int i = 0; i < de.length ; i++) {
buff.append(String.valueOf((char) de));
}
System.out.println("deCrypto :"+String.valueOf(buff.toString()));
}
} |
|