package steeven;
/*
用途: 简单加密/解密方法包装
作者: steeven@kali.com.cn
日期: 12/05/2001
感谢: http://www-900.ibm.com/developerworks/java/l-security/index.shtml
说明:
this class need jce, download here:
http://java.sun.com/security/index.html
*/
import java.security.*;
import javax.crypto.*;
public class crypt {
private static string algorithm="des"; //定义 加密算法,可用 des,desede,blowfish
static boolean debug = false;
static{
security.addprovider(new com.sun.crypto.provider.sunjce());
}
//生成密钥, 注意此步骤时间比较长
public static byte[] getkey() throws exception{
keygenerator keygen = keygenerator.getinstance(algorithm);
secretkey deskey = keygen.generatekey();
if (debug)
system.out.println("生成密钥:"+byte2hex(deskey.getencoded()));
return deskey.getencoded();
}
//加密
public static byte[] encode(byte[] input,byte[] key) throws exception{
secretkey deskey = new javax.crypto.spec.secretkeyspec(key,algorithm);
if (debug){
system.out.println("加密前的二进串:"+byte2hex(input));
system.out.println("加密前的字符串:"+new string(input));
}
cipher c1 = cipher.getinstance(algorithm);
c1.init(cipher.encrypt_mode,deskey);
byte[] cipherbyte=c1.dofinal(input);
if (debug)
system.out.println("加密后的二进串:"+byte2hex(cipherbyte));
return cipherbyte;
}
//解密
public static byte[] decode(byte[] input,byte[] key) throws exception{
secretkey deskey = new javax.crypto.spec.secretkeyspec(key,algorithm);
if (debug)
system.out.println("解密前的信息:"+byte2hex(input));
cipher c1 = cipher.getinstance(algorithm);
c1.init(cipher.decrypt_mode,deskey);
byte[] clearbyte=c1.dofinal(input);
if (debug){
system.out.println("解密后的二进串:"+byte2hex(clearbyte));
system.out.println("解密后的字符串:"+(new string(clearbyte)));
}
return clearbyte;
}
//md5()信息摘要, 不可逆
public static byte[] md5(byte[] input) throws exception{
java.security.messagedigest alg=java.security.messagedigest.getinstance("md5"); //or "sha-1"
if (debug){
system.out.println("摘要前的二进串:"+byte2hex(input));
system.out.println("摘要前的字符串:"+new string(input));
}
alg.update(input);
byte[] digest = alg.digest();
if (debug)
system.out.println("摘要后的二进串:"+byte2hex(digest));
return digest;
}
//字节码转换成16进制字符串
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) throws exception{
debug = true;
// byte[] key = getkey();
byte[] key = "好好学习".getbytes();
decode(encode("测试加密".getbytes(),key),key);
md5("测试加密".getbytes());
}
}