java常用工具类之DES和Base64加密解密类
一、DES加密和解密
packagecom.itjh.javaUtil;
importjava.io.UnsupportedEncodingException;
importjava.security.InvalidKeyException;
importjava.security.NoSuchAlgorithmException;
importjava.security.SecureRandom;
importjava.security.spec.InvalidKeySpecException;
importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjavax.crypto.KeyGenerator;
importjavax.crypto.NoSuchPaddingException;
importjavax.crypto.SecretKey;
importjavax.crypto.SecretKeyFactory;
importjavax.crypto.spec.DESKeySpec;
/**
*DES加密和解密。
*
*@author宋立君
*@date2014年07月03日
*/
publicclassDESUtil{
/**安全密钥*/
privateStringkeyData="ABCDEFGHIJKLMNOPQRSTWXYZabcdefghijklmnopqrstwxyz0123456789-_.";
/**
*功能:构造
*
*@author宋立君
*@date2014年07月03日
*/
publicDESUtil(){
}
/**
*功能:构造
*
*@author宋立君
*@date2014年07月03日
*@paramkeyData
*key
*/
publicDESUtil(Stringkey){
this.keyData=key;
}
/**
*功能:加密(UTF-8)
*
*@author宋立君
*@date2014年07月03日
*@paramsource
*源字符串
*@paramcharSet
*编码
*@returnString
*@throwsUnsupportedEncodingException
*编码异常
*/
publicStringencrypt(Stringsource)throwsUnsupportedEncodingException{
returnencrypt(source,"UTF-8");
}
/**
*
*功能:解密(UTF-8)
*
*@author宋立君
*@date2014年07月03日
*@paramencryptedData
*被加密后的字符串
*@returnString
*@throwsUnsupportedEncodingException
*编码异常
*/
publicStringdecrypt(StringencryptedData)
throwsUnsupportedEncodingException{
returndecrypt(encryptedData,"UTF-8");
}
/**
*功能:加密
*
*@author宋立君
*@date2014年07月03日
*@paramsource
*源字符串
*@paramcharSet
*编码
*@returnString
*@throwsUnsupportedEncodingException
*编码异常
*/
publicStringencrypt(Stringsource,StringcharSet)
throwsUnsupportedEncodingException{
Stringencrypt=null;
byte[]ret=encrypt(source.getBytes(charSet));
encrypt=newString(Base64.encode(ret));
returnencrypt;
}
/**
*
*功能:解密
*
*@author宋立君
*@date2014年07月03日
*@paramencryptedData
*被加密后的字符串
*@paramcharSet
*编码
*@returnString
*@throwsUnsupportedEncodingException
*编码异常
*/
publicStringdecrypt(StringencryptedData,StringcharSet)
throwsUnsupportedEncodingException{
StringdescryptedData=null;
byte[]ret=descrypt(Base64.decode(encryptedData.toCharArray()));
descryptedData=newString(ret,charSet);
returndescryptedData;
}
/**
*加密数据用生成的密钥加密原始数据
*
*@paramprimaryData
*原始数据
*@returnbyte[]
*@author宋立君
*@date2014年07月03日
*/
privatebyte[]encrypt(byte[]primaryData){
/**取得安全密钥*/
byterawKeyData[]=getKey();
/**DES算法要求有一个可信任的随机数源*/
SecureRandomsr=newSecureRandom();
/**使用原始密钥数据创建DESKeySpec对象*/
DESKeySpecdks=null;
try{
dks=newDESKeySpec(keyData.getBytes());
}catch(InvalidKeyExceptione){
e.printStackTrace();
}
/**创建一个密钥工厂*/
SecretKeyFactorykeyFactory=null;
try{
keyFactory=SecretKeyFactory.getInstance("DES");
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}
/**用密钥工厂把DESKeySpec转换成一个SecretKey对象*/
SecretKeykey=null;
try{
key=keyFactory.generateSecret(dks);
}catch(InvalidKeySpecExceptione){
e.printStackTrace();
}
/**Cipher对象实际完成加密操作*/
Ciphercipher=null;
try{
cipher=Cipher.getInstance("DES");
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}
/**用密钥初始化Cipher对象*/
try{
cipher.init(Cipher.ENCRYPT_MODE,key,sr);
}catch(InvalidKeyExceptione){
e.printStackTrace();
}
/**正式执行加密操作*/
byteencryptedData[]=null;
try{
encryptedData=cipher.doFinal(primaryData);
}catch(IllegalStateExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
/**返回加密数据*/
returnencryptedData;
}
/**
*用密钥解密数据
*
*@paramencryptedData
*加密后的数据
*@returnbyte[]
*@author宋立君
*@date2014年07月03日
*/
privatebyte[]descrypt(byte[]encryptedData){
/**DES算法要求有一个可信任的随机数源*/
SecureRandomsr=newSecureRandom();
/**取得安全密钥*/
byterawKeyData[]=getKey();
/**使用原始密钥数据创建DESKeySpec对象*/
DESKeySpecdks=null;
try{
dks=newDESKeySpec(keyData.getBytes());
}catch(InvalidKeyExceptione){
e.printStackTrace();
}
/**创建一个密钥工厂*/
SecretKeyFactorykeyFactory=null;
try{
keyFactory=SecretKeyFactory.getInstance("DES");
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}
/**用密钥工厂把DESKeySpec转换成一个SecretKey对象*/
SecretKeykey=null;
try{
key=keyFactory.generateSecret(dks);
}catch(InvalidKeySpecExceptione){
e.printStackTrace();
}
/**Cipher对象实际完成加密操作*/
Ciphercipher=null;
try{
cipher=Cipher.getInstance("DES");
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}
/**用密钥初始化Cipher对象*/
try{
cipher.init(Cipher.DECRYPT_MODE,key,sr);
}catch(InvalidKeyExceptione){
e.printStackTrace();
}
/**正式执行解密操作*/
bytedecryptedData[]=null;
try{
decryptedData=cipher.doFinal(encryptedData);
}catch(IllegalStateExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
returndecryptedData;
}
/**
*取得安全密钥此方法作废,因为每次key生成都不一样导致解密加密用的密钥都不一样,从而导致Givenfinalblocknot
*properlypadded错误.
*
*@returnbyte数组
*@author宋立君
*@date2014年07月03日
*/
privatebyte[]getKey(){
/**DES算法要求有一个可信任的随机数源*/
SecureRandomsr=newSecureRandom();
/**为我们选择的DES算法生成一个密钥生成器对象*/
KeyGeneratorkg=null;
try{
kg=KeyGenerator.getInstance("DES");
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}
kg.init(sr);
/**生成密钥工具类*/
SecretKeykey=kg.generateKey();
/**生成密钥byte数组*/
byterawKeyData[]=key.getEncoded();
returnrawKeyData;
}
}
二、Base64加密和解密
packagecom.itjh.javaUtil;
importjava.io.*;
/**
*Base64编码和解码。
*
*@author宋立君
*@date2014年07月03日
*/
publicclassBase64{
publicBase64(){
}
/**
*功能:编码字符串
*
*@author宋立君
*@date2014年07月03日
*@paramdata
*源字符串
*@returnString
*/
publicstaticStringencode(Stringdata){
returnnewString(encode(data.getBytes()));
}
/**
*功能:解码字符串
*
*@author宋立君
*@date2014年07月03日
*@paramdata
*源字符串
*@returnString
*/
publicstaticStringdecode(Stringdata){
returnnewString(decode(data.toCharArray()));
}
/**
*功能:编码byte[]
*
*@author宋立君
*@date2014年07月03日
*@paramdata
*源
*@returnchar[]
*/
publicstaticchar[]encode(byte[]data){
char[]out=newchar[((data.length+2)/3)*4];
for(inti=0,index=0;i<data.length;i+=3,index+=4){
booleanquad=false;
booleantrip=false;
intval=(0xFF&(int)data[i]);
val<<=8;
if((i+1)<data.length){
val|=(0xFF&(int)data[i+1]);
trip=true;
}
val<<=8;
if((i+2)<data.length){
val|=(0xFF&(int)data[i+2]);
quad=true;
}
out[index+3]=alphabet[(quad?(val&0x3F):64)];
val>>=6;
out[index+2]=alphabet[(trip?(val&0x3F):64)];
val>>=6;
out[index+1]=alphabet[val&0x3F];
val>>=6;
out[index+0]=alphabet[val&0x3F];
}
returnout;
}
/**
*功能:解码
*
*@author宋立君
*@date2014年07月03日
*@paramdata
*编码后的字符数组
*@returnbyte[]
*/
publicstaticbyte[]decode(char[]data){
inttempLen=data.length;
for(intix=0;ix<data.length;ix++){
if((data[ix]>255)||codes[data[ix]]<0){
--tempLen;//ignorenon-validcharsandpadding
}
}
//calculaterequiredlength:
//--3bytesforevery4validbase64chars
//--plus2bytesifthereare3extrabase64chars,
//orplus1byteifthereare2extra.
intlen=(tempLen/4)*3;
if((tempLen%4)==3){
len+=2;
}
if((tempLen%4)==2){
len+=1;
}
byte[]out=newbyte[len];
intshift=0;//#ofexcessbitsstoredinaccum
intaccum=0;//excessbits
intindex=0;
//wenowgothroughtheentirearray(NOTusingthe'tempLen'value)
for(intix=0;ix<data.length;ix++){
intvalue=(data[ix]>255)?-1:codes[data[ix]];
if(value>=0){//skipovernon-code
accum<<=6;//bitsshiftupby6eachtimethru
shift+=6;//loop,withnewbitsbeingputin
accum|=value;//atthebottom.
if(shift>=8){//wheneverthereare8ormoreshiftedin,
shift-=8;//writethemout(fromthetop,leavingany
out[index++]=//excessatthebottomfornextiteration.
(byte)((accum>>shift)&0xff);
}
}
}
//ifthereisSTILLsomethingwrongwejusthavetothrowupnow!
if(index!=out.length){
thrownewError("Miscalculateddatalength(wrote"+index
+"insteadof"+out.length+")");
}
returnout;
}
/**
*功能:编码文件
*
*@author宋立君
*@date2014年07月03日
*@paramfile
*源文件
*/
publicstaticvoidencode(Filefile)throwsIOException{
if(!file.exists()){
System.exit(0);
}
else{
byte[]decoded=readBytes(file);
char[]encoded=encode(decoded);
writeChars(file,encoded);
}
file=null;
}
/**
*功能:解码文件。
*
*@author宋立君
*@date2014年07月03日
*@paramfile
*源文件
*@throwsIOException
*/
publicstaticvoiddecode(Filefile)throwsIOException{
if(!file.exists()){
System.exit(0);
}else{
char[]encoded=readChars(file);
byte[]decoded=decode(encoded);
writeBytes(file,decoded);
}
file=null;
}
//
//codecharactersforvalues0..63
//
privatestaticchar[]alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
//
//lookuptableforconvertingbase64characterstovalueinrange0..63
//
privatestaticbyte[]codes=newbyte[256];
static{
for(inti=0;i<256;i++){
codes[i]=-1;
//LoggerUtil.debug(i+"&"+codes[i]+"");
}
for(inti='A';i<='Z';i++){
codes[i]=(byte)(i-'A');
//LoggerUtil.debug(i+"&"+codes[i]+"");
}
for(inti='a';i<='z';i++){
codes[i]=(byte)(26+i-'a');
//LoggerUtil.debug(i+"&"+codes[i]+"");
}
for(inti='0';i<='9';i++){
codes[i]=(byte)(52+i-'0');
//LoggerUtil.debug(i+"&"+codes[i]+"");
}
codes['+']=62;
codes['/']=63;
}
privatestaticbyte[]readBytes(Filefile)throwsIOException{
ByteArrayOutputStreambaos=newByteArrayOutputStream();
byte[]b=null;
InputStreamfis=null;
InputStreamis=null;
try{
fis=newFileInputStream(file);
is=newBufferedInputStream(fis);
intcount=0;
byte[]buf=newbyte[16384];
while((count=is.read(buf))!=-1){
if(count>0){
baos.write(buf,0,count);
}
}
b=baos.toByteArray();
}finally{
try{
if(fis!=null)
fis.close();
if(is!=null)
is.close();
if(baos!=null)
baos.close();
}catch(Exceptione){
System.out.println(e);
}
}
returnb;
}
privatestaticchar[]readChars(Filefile)throwsIOException{
CharArrayWritercaw=newCharArrayWriter();
Readerfr=null;
Readerin=null;
try{
fr=newFileReader(file);
in=newBufferedReader(fr);
intcount=0;
char[]buf=newchar[16384];
while((count=in.read(buf))!=-1){
if(count>0){
caw.write(buf,0,count);
}
}
}finally{
try{
if(caw!=null)
caw.close();
if(in!=null)
in.close();
if(fr!=null)
fr.close();
}catch(Exceptione){
System.out.println(e);
}
}
returncaw.toCharArray();
}
privatestaticvoidwriteBytes(Filefile,byte[]data)throwsIOException{
OutputStreamfos=null;
OutputStreamos=null;
try{
fos=newFileOutputStream(file);
os=newBufferedOutputStream(fos);
os.write(data);
}finally{
try{
if(os!=null)
os.close();
if(fos!=null)
fos.close();
}catch(Exceptione){
System.out.println(e);
}
}
}
privatestaticvoidwriteChars(Filefile,char[]data)throwsIOException{
Writerfos=null;
Writeros=null;
try{
fos=newFileWriter(file);
os=newBufferedWriter(fos);
os.write(data);
}finally{
try{
if(os!=null)
os.close();
if(fos!=null)
fos.close();
}catch(Exceptione){
e.printStackTrace();
}
}
}
///////////////////////////////////////////////////
//endoftestcode.
///////////////////////////////////////////////////
}
PS:关于加密技术,本站还提供了如下加密工具供大家参考使用:
BASE64编码解码工具:http://tools.jb51.net/transcoding/base64
MD5在线加密工具:http://tools.jb51.net/password/CreateMD5Password
Escape加密/解密工具:http://tools.jb51.net/password/escapepwd
在线SHA1加密工具:http://tools.jb51.net/password/sha1encode
短链(短网址)在线生成工具:http://tools.jb51.net/password/dwzcreate
短链(短网址)在线还原工具:http://tools.jb51.net/password/unshorturl
高强度密码生成器:http://tools.jb51.net/password/CreateStrongPassword
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短