java中如何使用RSA与AES实现加密解密
作者
这期内容当中小编将会给大家带来有关java中如何使用RSA与AES实现加密解密,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
1,RSA工具类:
packagecn.wangtao.utils; importorg.bouncycastle.jce.provider.BouncyCastleProvider; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importjavax.crypto.Cipher; importjava.io.ByteArrayOutputStream; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.ObjectOutputStream; importjava.security.*; importjava.security.interfaces.RSAPrivateKey; importjava.security.interfaces.RSAPublicKey; /** *@ClassNameRSAUtils *@Auth桃子 *@Date2019-6-2515:15 *@Version1.0 *@Description **/ publicclassRSAUtils{ privatestaticfinalStringRSA="RSA";//加密方式 privatestaticfinalLoggerlogger=LoggerFactory.getLogger(RSAUtils.class); //获取密钥 publicstaticKeyPairgetKey()throwsException{ try{ KeyPairGeneratorkeyPairGenerator=KeyPairGenerator.getInstance(RSA,newBouncyCastleProvider()); keyPairGenerator.initialize(2048);//初始化密钥长度 KeyPairkeyPair=keyPairGenerator.generateKeyPair();//生成密钥对 returnkeyPair; }catch(Exceptione){ logger.error("获取RSA秘钥对异常",e); thrownewException("获取RSA秘钥对异常",e); } } //利用公钥进行加密 publicstaticStringencryptStr(RSAPublicKeypublicKey,Stringstr)throwsException{ try{ Ciphercipher=Cipher.getInstance(RSA,newBouncyCastleProvider()); cipher.init(Cipher.ENCRYPT_MODE,publicKey); //加密 byte[]bytes=getBytes(str.getBytes(),cipher); //2进行转换成16进制 Stringresult=CommonUtils.parseByte2HexStr(bytes); returnresult; }catch(Exceptione){ logger.error("使用RSA公钥进行加密异常",e); thrownewException("使用RSA公钥进行加密异常",e); } } //利用私钥进行解密 publicstaticStringdecryptStr(RSAPrivateKeyprivateKey,Stringstr)throwsException{ try{ Ciphercipher=Cipher.getInstance(RSA,newBouncyCastleProvider()); cipher.init(Cipher.DECRYPT_MODE,privateKey);//用密钥初始化此Cipher对象 //16进制转换成2进制 byte[]bytes=CommonUtils.parseHexStr2Byte(str); //解密 byte[]bs=getBytes(bytes,cipher); Stringcontent=newString(bs,"utf-8"); returncontent; }catch(Exceptione){ logger.error("使用RSA私钥进行解密异常",e); thrownewException("使用RSA私钥进行解密异常",e); } } //通过cipher获取字节数组 publicstaticbyte[]getBytes(byte[]bytes,Ciphercipher)throwsException{ intblockSize=cipher.getBlockSize();//返回块的大小 intj=0; ByteArrayOutputStreambaos=newByteArrayOutputStream(); while(bytes.length-j*blockSize>0){//将二进制数据分块写入ByteArrayOutputStream中 if(bytes.length-j*blockSize>blockSize){ baos.write(cipher.doFinal(bytes,j*blockSize,blockSize)); }else{ baos.write(cipher.doFinal(bytes,j*blockSize,bytes.length-j*blockSize)); } j++; } baos.close(); byte[]byteArray=baos.toByteArray(); returnbyteArray; } //保存秘钥对到文件 publicvoidsaveRSAKey(StringfileName)throwsException{ FileOutputStreamfos=null; ObjectOutputStreamoos=null; try{ KeyPairkeyPair=getKey(); fos=newFileOutputStream(fileName); oos=newObjectOutputStream(fos);//对象序列号 oos.writeObject(keyPair); }catch(Exceptione){ logger.error("RSA秘钥对保存到文件异常[{}]",fileName,e); thrownewException("RSA秘钥对保存到文件异常",e); }finally{ if(oos!=null){ try{ oos.close(); }catch(IOExceptione1){ e1.printStackTrace(); } } if(fos!=null){ try{ fos.close(); }catch(IOExceptione1){ e1.printStackTrace(); } } } } }
2,CommonUtils通用工具类:
packagecn.wangtao.utils; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importjava.io.IOException; importjava.io.Reader; importjava.io.Writer; /** *@ClassNameCommonUtils *@Auth桃子 *@Date2019-6-2712:51 *@Version1.0 *@Description **/ publicclassCommonUtils{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(CommonUtils.class); //编码方式 publicstaticfinalStringCODE_TYPE="UTF-8"; //字符补全 privatestaticfinalString[]consult=newString[]{"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G"}; //关流 publicstaticvoidcloseReaderandWriter(Readerreader,Writerwriter){ if(writer!=null){ try{ writer.close(); }catch(IOExceptione){ logger.error("关闭输出流失败",e); } } if(reader!=null){ try{ reader.close(); }catch(IOExceptione){ logger.error("关闭输出流失败",e); } } } //将16进制转换为二进制 publicstaticbyte[]parseHexStr2Byte(StringhexStr){ if(hexStr.length()<1) returnnull; byte[]result=newbyte[hexStr.length()/2]; for(inti=0;i<hexStr.length()/2;i++){ inthigh=Integer.parseInt(hexStr.substring(i*2,i*2+1),16); intlow=Integer.parseInt(hexStr.substring(i*2+1,i*2+2),16); result[i]=(byte)(high*16+low); } returnresult; } //将二进制转换成16进制 publicstaticStringparseByte2HexStr(bytebuf[]){ StringBuffersb=newStringBuffer(); for(inti=0;i<buf.length;i++){ Stringhex=Integer.toHexString(buf[i]&0xFF); if(hex.length()==1){ hex='0'+hex; } sb.append(hex.toUpperCase()); } returnsb.toString(); } //补全字符 publicstaticStringcompletionCodeFor16Bytes(Stringstr)throwsException{ try{ intnum=str.getBytes(CODE_TYPE).length; intindex=num%16; //进行加密内容补全操作,加密内容应该为16字节的倍数,当不足16*n字节是进行补全,差一位时补全16+1位 //补全字符以$开始,$后一位代表$后补全字符位数,之后全部以0进行补全; if(index!=0){ StringBuffersbBuffer=newStringBuffer(str); if(16-index==1){ sbBuffer.append("$"+consult[16-1]+addStr(16-1-1)); }else{ sbBuffer.append("$"+consult[16-index-1]+addStr(16-index-1-1)); } str=sbBuffer.toString(); } returnstr; }catch(Exceptione){ logger.error("使用AES加密前补全字符异常",e); thrownewException("使用AES加密前补全字符异常",e); } } //追加字符 publicstaticStringaddStr(intnum){ StringBuffersbBuffer=newStringBuffer(""); for(inti=0;i<num;i++){ sbBuffer.append("0"); } returnsbBuffer.toString(); } //还原字符(进行字符判断) publicstaticStringresumeCodeOf16Bytes(Stringstr)throwsException{ intindexOf=str.lastIndexOf("$"); if(indexOf==-1){ returnstr; } Stringtrim=str.substring(indexOf+1,indexOf+2).trim(); intnum=0; for(inti=0;i<consult.length;i++){ if(trim.equals(consult[i])){ num=i; } } if(num==0){ returnstr; } returnstr.substring(0,indexOf).trim(); } }
3,AESUtils通用工具类:
packagecn.wangtao.utils; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importjavax.crypto.Cipher; importjavax.crypto.spec.SecretKeySpec; importjava.io.*; importjava.security.interfaces.RSAPrivateKey; importjava.util.Map; /** *@ClassNameAESUtils *@Auth桃子 *@Date2019-6-2712:05 *@Version1.0 *@Description **/ publicclassAESUtils{ privatestaticfinalLoggerlogger=LoggerFactory.getLogger(AESUtils.class); //填充类型 publicstaticfinalStringAES_TYPE="AES/ECB/PKCS5Padding"; privatestaticfinalStringAES="AES";//加密方式 publicstaticfinalStringDES_TYPE="DES/ECB/PKCS5Padding"; privatestaticfinalStringDES="DES";//加密方式 privatefinalStringdefaultDesKey="11112222";//8位 //对字符串加密 publicstaticStringencryptStr(Stringcontent,StringaesKey)throwsException{ try{ SecretKeySpeckey=newSecretKeySpec(aesKey.getBytes(),AES); Ciphercipher=Cipher.getInstance(AES_TYPE); cipher.init(Cipher.ENCRYPT_MODE,key); //字符补全 Stringcontent16Str=CommonUtils.completionCodeFor16Bytes(content); byte[]encryptedData=cipher.doFinal(content16Str.getBytes(CommonUtils.CODE_TYPE)); //2进制转换成16进制 StringhexStr=CommonUtils.parseByte2HexStr(encryptedData); returnhexStr; }catch(Exceptione){ logger.error("使用AES对字符串加密异常",e); thrownewException("使用AES对字符串加密异常",e); } } //对字符串解密 publicstaticStringdecryptStr(Stringcontent,StringaesKey)throwsException{ try{ //16进制转换成2进制 byte[]bytes=CommonUtils.parseHexStr2Byte(content); SecretKeySpeckey=newSecretKeySpec( aesKey.getBytes(),AES); Ciphercipher=Cipher.getInstance(AES_TYPE); cipher.init(Cipher.DECRYPT_MODE,key); byte[]decryptedData=cipher.doFinal(bytes); Stringresult=newString(decryptedData,CommonUtils.CODE_TYPE); //还原字符 StringorgResult=CommonUtils.resumeCodeOf16Bytes(result); returnorgResult; }catch(Exceptione){ logger.error("使用AES对字符串解密异常",e); thrownewException("使用AES对字符串解密异常",e); } } //对文件加密 publicstaticFileencryptFile(FileorgFile,FileencryptFile,Map<String,Object>context)throwsException{ logger.info("使用AES对文件加密开始,源文件地址[{}]加密后文件地址[{}]",orgFile.getPath(),encryptFile.getPath()); BufferedReaderbr=null; BufferedWriterbw=null; try{ //获取AESKEY,如果没有为默认 StringaesKey=(String)context.get(Dirt.AES_KEY); br=newBufferedReader(newFileReader(orgFile)); bw=(BufferedWriter)context.get(Dirt.BUFFEREDWRITER); if(null==bw){ bw=newBufferedWriter(newFileWriter(encryptFile)); } Stringlen=null; while(null!=(len=br.readLine())){ Stringencrypt=encryptStr(len,aesKey); bw.write(encrypt); bw.newLine(); bw.flush(); } logger.info("使用AES对文件加密结束,源文件地址[{}]加密后文件地址[{}]",orgFile.getPath(),encryptFile.getPath()); returnencryptFile; }catch(Exceptione){ logger.error("使用AES对文件加密异常,源文件地址[{}]加密后文件地址[{}]",orgFile.getPath(),encryptFile.getPath(),e); thrownewException("使用AES对文件加密异常",e); }finally{ CommonUtils.closeReaderandWriter(br,bw); } } //对文本解密,返回解密文件后的文件 publicstaticFiledecryptFile(Filedecryptfile,FileencryptFile,Map<String,Object>context)throwsException{ logger.info("使用AES对文件解密开始,源加密文件地址[{}]解密后文件地址[{}]",encryptFile.getPath(),decryptfile.getPath()); BufferedReaderbr=null; BufferedWriterbw=null; try{ if(decryptfile.exists()){ decryptfile.delete(); } //边读边加密边写 br=newBufferedReader(newFileReader(encryptFile)); bw=newBufferedWriter(newFileWriter(decryptfile)); Stringlen=null; StringaesKey=null; //判断是否加密 RSAPrivateKeyprivateKey=(RSAPrivateKey)context.get(Dirt.RSAPRIVATEKEY); if(null!=privateKey){ StringBuffersb=newStringBuffer(); while((len=br.readLine())!=null){ sb.append(len); if(len.equals("\n")||len.equals("")||len.equals("\r\n")||len.equals("\r")){ aesKey=RSAUtils.decryptStr(privateKey,sb.toString()); break; } } } if(null==aesKey){ aesKey=(String)context.get(Dirt.AES_KEY); } logger.info("aesKey[{}]",aesKey); if(aesKey!=null){ while((len=br.readLine())!=null){ Stringdecrypt=decryptStr(len,aesKey); bw.write(decrypt); bw.flush(); bw.newLine(); } } logger.info("使用AES对文件解密结束,源加密文件地址[{}]解密后文件地址[{}]",encryptFile.getPath(),decryptfile.getPath()); returndecryptfile; }catch(Exceptione){ logger.error("使用AES对文件解密异常,源加密文件地址[{}]解密后文件地址[{}]",encryptFile.getPath(),decryptfile.getPath(),e); thrownewException("使用AES对文件解密异常",e); }finally{ CommonUtils.closeReaderandWriter(br,bw); } } }
4,Dirt常量
packagecn.wangtao.utils; importjava.security.interfaces.RSAPublicKey; /** *@ClassNameDirt *@Auth桃子 *@Date2019-6-2714:20 *@Version1.0 *@Description **/ publicclassDirt{ publicstaticfinalStringUPLOADFILEURL="uploadFileUrl"; publicstaticfinalStringAES_KEY="aesKey"; publicstaticfinalStringRSAPUBLICKEY="rsaPublicKey"; publicstaticfinalStringRSAPRIVATEKEY="rsaPrivateKey"; publicfinalstaticStringRETURNCODE="returnCode"; publicfinalstaticStringRETURNMSG="returnMsg"; publicfinalstaticStringFILENAME="fileName"; publicfinalstaticStringORGFILENAME="orgFileName"; publicfinalstaticStringENCRYPTFILE="encryptFile"; publicstaticfinalStringBUFFEREDWRITER="bufferedWriter";//是为了在原始文件中进行补充加密 //返回码 publicfinalstaticStringSUCCESSCODE="000000"; publicfinalstaticStringFAILEDCODE="999999"; //加密文件所放的目录 publicfinalstaticStringBASELOCALDIR="XXX";//基本目录路径 publicfinalstaticStringENCRYPTLOCALDIR="encrypt";//加密文件目录
上述就是小编为大家分享的java中如何使用RSA与AES实现加密解密了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注恰卡编程网行业资讯频道。
目录
推荐阅读
0 条评论
本站已关闭游客评论,请登录或者注册后再评论吧~