Java实现的DES加密解密工具类实例
本文实例讲述了Java实现的DES加密解密工具类。分享给大家供大家参考,具体如下:
一个工具类,很常用,不做深入研究了,那来可直接用
DesUtil.java
packagelsy;
importjava.security.Key;
importjava.security.SecureRandom;
importjavax.crypto.Cipher;
importjavax.crypto.KeyGenerator;
importjavax.crypto.SecretKey;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
publicclassDesUtil{
/**
*@paramargs
*/
publicstaticvoidmain(String[]args){
//以下是加密方法algorithm="AES"的测试
System.out.println(DesUtil.getInstance("lushuaiyin").getEnCodeString("hello"));
//输出LDewGAZkmWHeYFjBz56ylw==
//将上面的密文解密:
System.out.println(DesUtil.getInstance("lushuaiyin").getDecodeString("LDewGAZkmWHeYFjBz56ylw=="));
//输出hello
//改变密钥测试
System.out.println(DesUtil.getInstance("suolong").getEnCodeString("hello"));
//输出/RLowOJ+Fr3KdMcdJeNatg==
System.out.println(DesUtil.getInstance("suolong").getDecodeString("/RLowOJ+Fr3KdMcdJeNatg=="));
//输出hello
//如果使用不正确的密钥解密,将会:
System.out.println(DesUtil.getInstance("suolong").getDecodeString("LDewGAZkmWHeYFjBz56ylw=="));
}
privateSecretKeykey=null;//密钥
//定义加密算法,可用DES,DESede,Blowfish,AES
//不同的加密方式结果会不同
privatestaticStringalgorithm="AES";
privatestaticDesUtildesUtil=null;
publicDesUtil(){}
publicstaticDesUtilgetInstance(StringstrKey){
desUtil=newDesUtil();
desUtil.createKey(strKey);
returndesUtil;
}
/**
*algorithm算法
*@paramstrKey
*/
publicvoidcreateKey(StringstrKey){
try{
KeyGeneratorkg=KeyGenerator.getInstance(DesUtil.algorithm);
byte[]bt=strKey.getBytes("UTF-8");
SecureRandomsr=newSecureRandom(bt);
kg.init(sr);
this.setKey(kg.generateKey());
}catch(Exceptione){
}
}
/**
*加密方法,返回密文
*cipher密码
*@paramdataStr
*/
publicStringgetEnCodeString(StringdataStr){
byte[]miwen=null;//密文
byte[]mingwen=null;//明文
Ciphercipher;
Stringresult="";//密文字符串
try{
mingwen=dataStr.getBytes("UTF-8");
cipher=Cipher.getInstance(DesUtil.algorithm);
cipher.init(Cipher.ENCRYPT_MODE,this.getKey());
miwen=cipher.doFinal(mingwen);
BASE64Encoderbase64en=newBASE64Encoder();
result=base64en.encodeBuffer(miwen);//或者可以用下面的方法得到密文,结果是不一样的,都可以正常解密
//result=byte2hex(miwen);//密文结果类似2C:37:B0:18:06:64:99:61:DE:60:58:C1:CF:9E:B2:97
}catch(Exceptione){
e.printStackTrace();
}
returnresult;
}
/**
*解密方法,返回明文
*@paramcodeStr
*@return
*/
publicStringgetDecodeString(StringcodeStr){
BASE64Decoderbase64De=newBASE64Decoder();
byte[]miwen=null;
byte[]mingwen=null;
StringresultData="";//返回的明文
Ciphercipher;
try{
miwen=base64De.decodeBuffer(codeStr);
cipher=Cipher.getInstance(DesUtil.algorithm);
cipher.init(Cipher.DECRYPT_MODE,this.getKey());
mingwen=cipher.doFinal(miwen);
resultData=newString(mingwen,"UTF-8");
}catch(Exceptione){
return"密钥不正确或其他原因导致异常,无法解密!";
}
returnresultData;
}
//二行制转字符串
publicStringbyte2hex(byte[]b){
Stringhs="";
Stringstmp="";
for(intn=0;n
运行结果:
LDewGAZkmWHeYFjBz56ylw==
hello
/RLowOJ+Fr3KdMcdJeNatg==
hello
密钥不正确或其他原因导致异常,无法解密!
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
在线DES加密/解密工具: