Java加密解密工具(适用于JavaSE/JavaEE/Android)
本文实例为大家分享了一个适用于JavaSE/JavaEE/Android的Java加密解密工具,供大家学习,具体内容如下
packagelongshu.utils.security;
importjava.lang.reflect.Method;
importjava.security.InvalidKeyException;
importjava.security.Key;
importjava.security.MessageDigest;
importjava.security.NoSuchAlgorithmException;
importjava.security.SecureRandom;
importjavax.crypto.BadPaddingException;
importjavax.crypto.Cipher;
importjavax.crypto.IllegalBlockSizeException;
importjavax.crypto.KeyGenerator;
importjavax.crypto.NoSuchPaddingException;
importjavax.crypto.SecretKey;
importjavax.crypto.spec.SecretKeySpec;
/**
*Java加密解密工具.
*JavaSE/JavaEE/Android都适用
*
*@authorlongshu2016年4月13日
*/
publicclassEncryptDecrypt{
//无需创建对象
privateEncryptDecrypt(){
}
/**
*SHA1加密Bit数据
*@paramsourcebyte数组
*@return加密后的byte数组
*/
publicstaticbyte[]SHA1Bit(byte[]source){
try{
MessageDigestsha1Digest=MessageDigest.getInstance("SHA-1");
sha1Digest.update(source);
bytetargetDigest[]=sha1Digest.digest();
returntargetDigest;
}catch(NoSuchAlgorithmExceptione){
thrownewRuntimeException(e);
}
}
/**
*SHA1加密字符串数据
*@paramsource要加密的字符串
*@return加密后的字符串
*/
publicstaticStringSHA1(Stringsource){
returnbyte2HexStr(SHA1Bit(source.getBytes()));
}
/**
*MD5加密Bit数据
*@paramsourcebyte数组
*@return加密后的byte数组
*/
publicstaticbyte[]MD5Bit(byte[]source){
try{
//获得MD5摘要算法的MessageDigest对象
MessageDigestmd5Digest=MessageDigest.getInstance("MD5");
//使用指定的字节更新摘要
md5Digest.update(source);
//获得密文
returnmd5Digest.digest();
}catch(NoSuchAlgorithmExceptione){
thrownewRuntimeException(e);
}
}
/**
*MD5加密字符串,32位长
*@paramsource要加密的内容
*@return加密后的内容
*/
publicstaticStringMD5(Stringsource){
returnbyte2HexStr(MD5Bit(source.getBytes()));
}
/**
*BASE64编码
*@paramsource要编码的字符串
*@return编码过的字符串
*/
publicstaticStringencodeBASE64(Stringsource){
Class<?>clazz=null;
MethodencodeMethod=null;
try{//优先使用第三方库
clazz=Class.forName("org.apache.commons.codec.binary.Base64");
encodeMethod=clazz.getMethod("encodeBase64",byte[].class);
System.out.println("encodeBASE64-->"+clazz);
System.out.println("encodeMethod-->"+encodeMethod);
//反射方法静态方法执行无需对象
returnnewString((byte[])encodeMethod.invoke(null,source.getBytes()));
}catch(ClassNotFoundExceptione){
Stringvm=System.getProperty("java.vm.name");
System.out.println(vm);
try{
if("Dalvik".equals(vm)){//Android
clazz=Class.forName("android.util.Base64");
//byte[]Base64.encode(byte[]input,intflags)
encodeMethod=clazz.getMethod("encode",byte[].class,int.class);
System.out.println("encodeBASE64-->"+clazz);
System.out.println("encodeMethod-->"+encodeMethod);
returnnewString((byte[])encodeMethod.invoke(null,source.getBytes(),0));
}else{//JavaSE/JavaEE
clazz=Class.forName("sun.misc.BASE64Encoder");
encodeMethod=clazz.getMethod("encode",byte[].class);
System.out.println("encodeBASE64-->"+clazz);
System.out.println("encodeMethod-->"+encodeMethod);
return(String)encodeMethod.invoke(clazz.newInstance(),source.getBytes());
}
}catch(ClassNotFoundExceptione1){
returnnull;
}catch(Exceptione1){
returnnull;
}
}catch(Exceptione){
returnnull;
}
/*
*Android
*android.util.Base64
*/
//returnBase64.encodeToString(source,Base64.DEFAULT);
//returnnewString(Base64.encode(source.getBytes(),Base64.DEFAULT));
/*
*JavaSE/JavaEE
*/
//sun.misc.BASE64Encoder
//BASE64Encoderencoder=newBASE64Encoder();
//returnencoder.encode(source.getBytes());
//org.apache.commons.codec.binary.Base64
//returnnewString(Base64.encodeBase64(source.getBytes()));
}
/**
*BASE64解码
*@paramencodeSource编码过的字符串
*@return编码前的字符串
*/
publicstaticStringdecodeBASE64(StringencodeSource){
Class<?>clazz=null;
MethoddecodeMethod=null;
try{//优先使用第三方库
clazz=Class.forName("org.apache.commons.codec.binary.Base64");
decodeMethod=clazz.getMethod("decodeBase64",byte[].class);
System.out.println("decodeBASE64-->"+clazz);
System.out.println("decodeMethod-->"+decodeMethod);
//反射方法静态方法执行无需对象
returnnewString((byte[])decodeMethod.invoke(null,encodeSource.getBytes()));
}catch(ClassNotFoundExceptione){
Stringvm=System.getProperty("java.vm.name");
System.out.println(vm);
try{
if("Dalvik".equals(vm)){//Android
clazz=Class.forName("android.util.Base64");
//byte[]Base64.decode(byte[]input,intflags)
decodeMethod=clazz.getMethod("decode",byte[].class,int.class);
System.out.println("decodeBASE64-->"+clazz);
System.out.println("decodeMethod-->"+decodeMethod);
returnnewString((byte[])decodeMethod.invoke(null,encodeSource.getBytes(),0));
}else{//JavaSE/JavaEE
clazz=Class.forName("sun.misc.BASE64Decoder");
decodeMethod=clazz.getMethod("decodeBuffer",String.class);
System.out.println("decodeBASE64-->"+clazz);
System.out.println("decodeMethod-->"+decodeMethod);
returnnewString((byte[])decodeMethod.invoke(clazz.newInstance(),encodeSource));
}
}catch(ClassNotFoundExceptione1){
returnnull;
}catch(Exceptione1){
returnnull;
}
}catch(Exceptione){
returnnull;
}
/*
*Android
*android.util.Base64
*/
//returnnew
//String(Base64.decode(encodeSource.getBytes(),Base64.DEFAULT));
/*
*JavaSE/JavaEE
*/
//sun.misc.BASE64Decoder
//try{
//BASE64Decoderdecoder=newBASE64Decoder();
//returnnewString(decoder.decodeBuffer(encodeSource));
//}catch(IOExceptione){
//thrownewRuntimeException(e);
//}
//org.apache.commons.codec.binary.Base64
//returnnewString(Base64.decodeBase64(encodeSource.getBytes()));
}
/**
*AES加密
*@paramcontent待加密的内容
*@parampassword加密密码
*@return
*/
publicstaticbyte[]encryptBitAES(byte[]content,Stringpassword){
try{
CipherencryptCipher=Cipher.getInstance("AES/ECB/PKCS5Padding");//创建密码器
encryptCipher.init(Cipher.ENCRYPT_MODE,getKey(password));//初始化
byte[]result=encryptCipher.doFinal(content);
returnresult;//加密
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}catch(InvalidKeyExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*AES解密
*@paramcontent待解密内容
*@parampassword解密密钥
*@return
*/
publicstaticbyte[]decryptBitAES(byte[]content,Stringpassword){
try{
CipherdecryptCipher=Cipher.getInstance("AES/ECB/PKCS5Padding");//创建密码器
decryptCipher.init(Cipher.DECRYPT_MODE,getKey(password));//初始化
byte[]result=decryptCipher.doFinal(content);
returnresult;//加密结果
}catch(InvalidKeyExceptione){
e.printStackTrace();
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*AES字符串加密
*@paramcontent待加密的内容
*@parampassword加密密码
*@return
*/
publicstaticStringencryptAES(Stringcontent,Stringpassword){
returnbyte2HexStr(encryptBitAES(content.getBytes(),password));
}
/**
*AES字符串解密
*@paramcontent待解密内容
*@parampassword解密密钥
*@return
*/
publicstaticStringdecryptAES(Stringcontent,Stringpassword){
returnnewString(decryptBitAES(hexStr2Bytes(content),password));
}
/**
*从指定字符串生成密钥
*@parampassword构成该秘钥的字符串
*@return生成的密钥
*@throwsNoSuchAlgorithmException
*/
privatestaticKeygetKey(Stringpassword)throwsNoSuchAlgorithmException{
SecureRandomsecureRandom=newSecureRandom(password.getBytes());
//生成KEY
KeyGeneratorkgen=KeyGenerator.getInstance("AES");
kgen.init(128,secureRandom);
SecretKeysecretKey=kgen.generateKey();
byte[]enCodeFormat=secretKey.getEncoded();
//转换KEY
SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");
returnkey;
}
/**
*将byte数组转换为表示16进制值的字符串.
*如:byte[]{8,18}转换为:0812
*和byte[]hexStr2Bytes(StringstrIn)互为可逆的转换过程.
*@parambytes需要转换的byte数组
*@return转换后的字符串
*/
publicstaticStringbyte2HexStr(byte[]bytes){
intbytesLen=bytes.length;
//每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍
StringBufferhexString=newStringBuffer(bytesLen*2);
for(inti=0;i<bytesLen;i++){
//将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
Stringhex=Integer.toHexString(bytes[i]&0xFF);
if(hex.length()<2){
hexString.append(0);//如果为1位前面补个0
}
hexString.append(hex);
}
returnhexString.toString();
}
/**
*将表示16进制值的字符串转换为byte数组,
*和Stringbyte2HexStr(byte[]bytes)互为可逆的转换过程.
*@parambytes
*@return转换后的byte数组
*/
publicstaticbyte[]hexStr2Bytes(StringstrIn){
byte[]arrB=strIn.getBytes();
intiLen=arrB.length;
//两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[]arrOut=newbyte[iLen/2];
for(inti=0;i<iLen;i=i+2){
StringstrTmp=newString(arrB,i,2);
arrOut[i/2]=(byte)Integer.parseInt(strTmp,16);
}
returnarrOut;
}
}
以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。