java的加密解密.docx
《java的加密解密.docx》由会员分享,可在线阅读,更多相关《java的加密解密.docx(16页珍藏版)》请在冰点文库上搜索。
java的加密解密
bytealgorithm加密string解密import
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;
publicclassDESEncryptTest{
privatestaticfinalStringDES_ALGORITHM="DES";
/**
*DES加密
*@paramplainData
*@paramsecretKey
*@return
*@throwsException
*/
publicStringencryption(StringplainData,StringsecretKey)throwsException{
Ciphercipher=null;
try{
cipher=Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE,generateKey(secretKey));
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}catch(InvalidKeyExceptione){
}
try{
//为了防止解密时报javax.crypto.IllegalBlockSizeException:
Inputlengthmustbemultipleof8whendecryptingwithpaddedcipher异常,
//不能把加密后的字节数组直接转换成字符串
byte[]buf=cipher.doFinal(plainData.getBytes());
returnBase64Utils.encode(buf);
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
thrownewException("IllegalBlockSizeException",e);
}catch(BadPaddingExceptione){
e.printStackTrace();
thrownewException("BadPaddingException",e);
}
}
/**
*DES解密
*@paramsecretData
*@paramsecretKey
*@return
*@throwsException
*/
publicStringdecryption(StringsecretData,StringsecretKey)throwsException{
Ciphercipher=null;
try{
cipher=Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE,generateKey(secretKey));
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
thrownewException("NoSuchAlgorithmException",e);
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
thrownewException("NoSuchPaddingException",e);
}catch(InvalidKeyExceptione){
e.printStackTrace();
thrownewException("InvalidKeyException",e);
}
try{
byte[]buf=cipher.doFinal(Base64Utils.decode(secretData.toCharArray()));
returnnewString(buf);
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
thrownewException("IllegalBlockSizeException",e);
}catch(BadPaddingExceptione){
e.printStackTrace();
thrownewException("BadPaddingException",e);
}
}
/**
*获得秘密密钥
*
*@paramsecretKey
*@return
*@throwsNoSuchAlgorithmException
*/
privateSecretKeygenerateKey(StringsecretKey)throwsNoSuchAlgorithmException{
SecureRandomsecureRandom=newSecureRandom(secretKey.getBytes());
//为我们选择的DES算法生成一个KeyGenerator对象
KeyGeneratorkg=null;
try{
kg=KeyGenerator.getInstance(DES_ALGORITHM);
}catch(NoSuchAlgorithmExceptione){
}
kg.init(secureRandom);
//kg.init(56,secureRandom);
//生成密钥
returnkg.generateKey();
}
publicstaticvoidmain(String[]a)throwsException{
Stringinput="cy11Xlbrmzyh:
604:
301:
1353064296";
Stringkey="37d5aed075525d4fa0fe635231cba447";
DESEncryptTestdes=newDESEncryptTest();
Stringresult=des.encryption(input,key);
System.out.println(result);
System.out.println(des.decryption(result,key));
}
staticclassBase64Utils{
staticprivatechar[]alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
staticprivatebyte[]codes=newbyte[256];
static{
for(inti=0;i<256;i++)
codes[i]=-1;
for(inti='A';i<='Z';i++)
codes[i]=(byte)(i-'A');
for(inti='a';i<='z';i++)
codes[i]=(byte)(26+i-'a');
for(inti='0';i<='9';i++)
codes[i]=(byte)(52+i-'0');
codes['+']=62;
codes['/']=63;
}
/**
*将原始数据编码为base64编码
*/
staticpublicStringencode(byte[]data){
char[]out=newchar[((data.length+2)/3)*4];
for(inti=0,index=0;ibooleanquad=false;
booleantrip=false;
intval=(0xFF&(int)data[i]);
val<<=8;
if((i+1)val|=(0xFF&(int)data[i+1]);
trip=true;
}
val<<=8;
if((i+2)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];
}
returnnewString(out);
}
/**
*将base64编码的数据解码成原始数据
*/
staticpublicbyte[]decode(char[]data){
intlen=((data.length+3)/4)*3;
if(data.length>0&&data[data.length-1]=='=')
--len;
if(data.length>1&&data[data.length-2]=='=')
--len;
byte[]out=newbyte[len];
intshift=0;
intaccum=0;
intindex=0;
for(intix=0;ixintvalue=codes[data[ix]&0xFF];
if(value>=0){
accum<<=6;
shift+=6;
accum|=value;
if(shift>=8){
shift-=8;
out[index++]=(byte)((accum>>shift)&0xff);
}
}
}
if(index!
=out.length)
thrownewError("miscalculateddatalength!
");
returnout;
}
}
}
KKKKkkkkKKKKKKKKKKKKKKK
/*在java中调用sun公司提供的3DES加密解密算法时,需要使用到$JAVA_HOME/jre/lib/目录下如下的4个jar包:
jce.jarsecurity/US_export_policy.jarsecurity/local_policy.jarext/sunjce_provider.jar
Java运行时会自动加载这些包,因此对于带main函数的应用程序不需要设置到CLASSPATH环境变量中。
对于WEB应用,不需要把这些包加到WEB-INF/lib目录下。
以下是java中调用sun公司提供的3DES加密解密算法的样本代码:
*/
packagecom.aaa.aaa;
importjava.security.*;
importjavax.crypto.*;
importjavax.crypto.spec.SecretKeySpec;
publicclassThreeDES{
privatestaticfinalStringAlgorithm="DESede";//定义加密算法,可用
//DES,DESede,Blowfish
privatestaticfinalbyte[]keyBase={0x11,0x22,0x4F,0x58,
(byte)0x88,0x10,0x40,0x38,0x28,0x25,0x79,0x51,(byte)0xCB,
(byte)0xDD,0x55,0x66,0x77,0x29,0x74,(byte)0x98,0x30,0x40,
0x36,(byte)0xE2}; //24个byte的密钥
//keybyte为加密密钥,长度为24字节
//src为被加密的数据缓冲区(源)
/**
*加密
*/
publicstaticbyte[]encryptMode(byte[]src){
try{//生成密钥
SecretKeydeskey=newSecretKeySpec(keyBase,Algorithm);
//加密
Cipherc1=Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE,deskey);
returnc1.doFinal(src);
}catch(java.security.NoSuchAlgorithmExceptione1){
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingExceptione2){
e2.printStackTrace();
}catch(java.lang.Exceptione3){
e3.printStackTrace();
}
returnnull;
}
//keybyte为加密密钥,长度为24字节
//src为加密后的缓冲区
publicstaticbyte[]decryptMode(byte[]src){
try{//生成密钥
SecretKeydeskey=newSecretKeySpec(keyBase,Algorithm);
//解密
Cipherc1=Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE,deskey);
returnc1.doFinal(src);
}catch(java.security.NoSuchAlgorithmExceptione1){
e1.printStackTrace();
}catch(javax.crypto.NoSuchPaddingExceptione2){
e2.printStackTrace();
}catch(java.lang.Exceptione3){
e3.printStackTrace();
}
returnnull;
}
//转换成十六进制字符串
publicstaticStringbyte2hex(byte[]b){
Stringhs="";
Stringstmp="";
for(intn=0;n stmp=(java.lang.Integer.toHexString(b[n]&0XFF));
if(stmp.length()==1)
hs=hs+"0"+stmp;
else
hs=hs+stmp;
if(n hs=hs+":
";
}
returnhs.toUpperCase();
}
publicstaticvoidmain(String[]args){
//添加新安全算法,如果用JCE就要把它添加进去
Security.addProvider(newcom.sun.crypto.provider.SunJCE());
finalbyte[]keyBytes={0x11,0x22,0x4F,0x58,(byte)0x88,0x10,
0x40,0x38,0x28,0x25,0x79,0x51,(byte)0xCB,(byte)0xDD,
0x55,0x66,0x77,0x29,0x74,(byte)0x98,0x30,0x40,0x36,
(byte)0xE2};
//24字节的密钥
StringszSrc="Thisisa3DEStest.测试";
System.out.println("加密前的字符串:
"+szSrc);
byte[]encoded=encryptMode(szSrc.getBytes());
System.out.println("加密后的字符串:
"+newString(encoded));
byte[]srcBytes=decryptMode(encoded);
System.out.println("解密后的字符串:
"+(newString(srcBytes)));
}
}
ddddddddddddddddddddd
packagecom.snailteam.adserver.until;
importjava.io.UnsupportedEncodingException;
importjava.security.InvalidKeyException;
importjava.security.NoSuchAlgorithmException;
importjava.security.SecureRandom;
importjavax.crypto.*;
importjavax.crypto.spec.SecretKeySpec;
/**
*@author:
xiaofancn
*@version:
2011-11-11上午11:
02:
22
*
*/
publicclassTool3DES{
privatestaticfinalStringAlgorithm="DESede";//定义加密算法,可用
privatestaticfinalintKeysize=168;
/**
*将byte[]转化成16进制字符串
*@parambuf
*@return
*/
publicstaticStringparseByte2HexStr(bytebuf[]){
StringBuffersb=newStringBuffer();
for(inti=0;iStringhex=Integer.toHexString(buf[i]&0xFF);
if(hex.length()==1){
hex='0'+hex;
}
sb.append(hex.toUpperCase());
}
returnsb.toString();
}
/**
*将16进制字符串转化成byte[]
*@parambuf
*@return
*/
publicstaticbyte[]parseHexStr2Byte(StringhexStr){
if(hexStr.length()<1)
returnnull;
byte[]result=newbyte[hexStr.length()/2];
for(inti=0;iinthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16);
intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),