亚洲情人网-亚洲情人-亚洲欧洲综合-亚洲欧洲自拍-欧美专区亚洲

數(shù)據(jù)加密方式(數(shù)據(jù)加密方式發(fā)展)

  • 生活
  • 2023-04-21 16:16
一、Java常用加密方式Base64加密算法(編碼方式)MD5加密(消息摘要算法,驗證信息完整性)對稱加密算法非對稱加密算法數(shù)字簽名算法數(shù)字證書

二、分類

按加密算法是否需要key被分為兩類:

不基于key的有:Base64算法、MD5基于key的有:對稱加密算法、非對稱加密算法、數(shù)字簽名算法、數(shù)字證書、HMAC、RC4(對稱加密)

按加密算法是否可逆被分為兩類:

單向加密算法(不可解密):MD5、SHA、HMAC非單項加密算法(可解密):BASE64、對稱加密算法、非對稱加密算法、數(shù)字簽名算法、數(shù)字證書

三、算法介紹

1.對稱加密

對稱加密是最快速、最簡單的一種加密方式,加密(encryption)與解密(decryption)用的是同樣的密鑰(secretkey)。對稱加密有很多種算法,由于它效率很高,所以被廣泛使用在很多加密協(xié)議的核心當中。

對稱加密通常使用的是相對較小的密鑰,一般小于256bit。因為密鑰越大,加密越強,但加密與解密的過程越慢。如果你只用1bit來做這個密鑰,那***們可以先試著用0來解密,不行的話就再用1解;但如果你的密鑰有1MB大,***們可能永遠也無法破解,但加密和解密的過程要花費很長的時間。密鑰的大小既要照顧到安全性,也要照顧到效率,是一個trade-off。

DES(DataEncryptionStandard)和TripleDES是對稱加密的兩種實現(xiàn)。

DES和TripleDES基本算法一致,只是TripleDES算法提供的key位數(shù)更多,加密可靠性更高。

DES使用的密鑰key為8字節(jié),初始向量IV也是8字節(jié)。

TripleDES使用24字節(jié)的key,初始向量IV也是8字節(jié)。

兩種算法都是以8字節(jié)為一個塊進行加密,一個數(shù)據(jù)塊一個數(shù)據(jù)塊的加密,一個8字節(jié)的明文加密后的密文也是8字節(jié)。如果明文長度不為8字節(jié)的整數(shù)倍,添加值為0的字節(jié)湊滿8字節(jié)整數(shù)倍。所以加密后的密文長度一定為8字節(jié)的整數(shù)倍

下面舉個例子:

importjava.security.InvalidKeyException;importjava.security.Key;importjava.security.NoSuchAlgorithmException;importjava.security.SecureRandom;importjava.security.spec.InvalidKeySpecException;importjavax.crypto.Cipher;importjavax.crypto.SecretKey;importjavax.crypto.SecretKeyFactory;importjavax.crypto.spec.DESKeySpec;importorg.apache.commons.codec.binary.Base64;publicclassDESDemo{//算法名稱publicstaticfinalStringKEY_ALGORITHM="DES";//算法名稱/加密模式/填充方式//DES共有四種工作模式-->>ECB:電子密碼本模式、CBC:加密分組鏈接模式、CFB:加密反饋模式、OFB:輸出反饋模式publicstaticfinalStringCIPHER_ALGORITHM="DES/ECB/NoPadding";/****生成密鑰key對象**@paramKeyStr*密鑰字符串*@return密鑰對象*@throwsInvalidKeyException*@throwsNoSuchAlgorithmException*@throwsInvalidKeySpecException*@throwsException*/privatestaticSecretKeykeyGenerator(StringkeyStr)throwsException{byteinput[]=HexString2Bytes(keyStr);DESKeySpecdesKey=newDESKeySpec(input);//創(chuàng)建一個密匙工廠,然后用它把DESKeySpec轉換成SecretKeyFactorykeyFactory=SecretKeyFactory.getInstance("DES");SecretKeysecurekey=keyFactory.generateSecret(desKey);returnsecurekey;}privatestaticintparse(charc){if(c>='a')return(c-'a'+10)&0x0f;if(c>='A')return(c-'A'+10)&0x0f;return(c-'0')&0x0f;}//從十六進制字符串到字節(jié)數(shù)組轉換publicstaticbyte[]HexString2Bytes(Stringhexstr){byte[]b=newbyte[hexstr.length()/2];intj=0;for(inti=0;i<b.length;i++){charc0=hexstr.charAt(j++);charc1=hexstr.charAt(j++);b[i]=(byte)((parse(c0)<<4)|parse(c1));}returnb;}/***加密數(shù)據(jù)**@paramdata*待加密數(shù)據(jù)*@paramkey*密鑰*@return加密后的數(shù)據(jù)*/publicstaticStringencrypt(Stringdata,Stringkey)throwsException{Keydeskey=keyGenerator(key);//實例化Cipher對象,它用于完成實際的加密操作Ciphercipher=Cipher.getInstance(CIPHER_ALGORITHM);SecureRandomrandom=newSecureRandom();//初始化Cipher對象,設置為加密模式cipher.init(Cipher.ENCRYPT_MODE,deskey,random);byte[]results=cipher.doFinal(data.getBytes());//該部分是為了與加解密在線測試網(wǎng)站(http://tripledes.online-domain-tools.com/)的十六進制結果進行核對for(inti=0;i<results.length;i++){System.out.print(results[i]+"");}System.out.println();//執(zhí)行加密操作。加密后的結果通常都會用Base64編碼進行傳輸returnBase64.encodeBase64String(results);}/***解密數(shù)據(jù)**@paramdata*待解密數(shù)據(jù)*@paramkey*密鑰*@return解密后的數(shù)據(jù)*/publicstaticStringdecrypt(Stringdata,Stringkey)throwsException{Keydeskey=keyGenerator(key);Ciphercipher=Cipher.getInstance(CIPHER_ALGORITHM);//初始化Cipher對象,設置為解密模式cipher.init(Cipher.DECRYPT_MODE,deskey);//執(zhí)行解密操作returnnewString(cipher.doFinal(Base64.decodeBase64(data)));}publicstaticvoidmain(String[]args)throwsException{Stringsource="helloittx";System.out.println("原文:"+source);Stringkey="A1B2C3D4E5F60708";StringencryptData=encrypt(source,key);System.out.println("加密后:"+encryptData);StringdecryptData=decrypt(encryptData,key);System.out.println("解密后:"+decryptData);}}2.非對稱加密

非對稱加密為數(shù)據(jù)的加密與解密提供了一個非常安全的***,它使用了一對密鑰,公鑰(publickey)和私鑰(privatekey)。私鑰只能由一方安全保管,不能外泄,而公鑰則可以發(fā)給任何請求它的人。非對稱加密使用這對密鑰中的一個進行加密,而解密則需要另一個密鑰。比如,你向銀行請求公鑰,銀行將公鑰發(fā)給你,你使用公鑰對消息加密,那么只有私鑰的持有人–銀行才能對你的消息解密。與對稱加密不同的是,銀行不需要將私鑰通過網(wǎng)絡發(fā)送出去,因此安全性大大提高。

目前最常用的非對稱加密算法是RSA算法,是Rivest,Shamir,和Adleman于1978年發(fā)明,他們那時都是在MIT。請看下面的例子:

importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.math.BigInteger;importjava.security.Key;importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.SecureRandom;importjava.security.spec.RSAPrivateCrtKeySpec;importjava.security.spec.RSAPublicKeySpec;importjavax.crypto.Cipher;importcom.lxh.rsatest.HexUtil;importDecoder.BASE64Decoder;importDecoder.BASE64Encoder;publicclassRSAEncrypt{/**指定加密算法為DESede*/privatestaticStringALGORITHM="RSA";/**指定key的大小*/privatestaticintKEYSIZE=1024;/**指定公鑰存放文件*/privatestaticStringPUBLIC_KEY_FILE="public.keystore";/**指定私鑰存放文件*/privatestaticStringPRIVATE_KEY_FILE="private.keystore";/***生成密鑰對*/privatestaticvoidgenerateKeyPair()throwsException{/**RSA算法要求有一個可信任的隨機數(shù)源*/SecureRandomsr=newSecureRandom();/**為RSA算法創(chuàng)建一個KeyPairGenerator對象*/KeyPairGeneratorkpg=KeyPairGenerator.getInstance(ALGORITHM);/**利用上面的隨機數(shù)據(jù)源初始化這個KeyPairGenerator對象*/kpg.initialize(KEYSIZE,sr);/**生成密匙對*/KeyPairkp=kpg.generateKeyPair();/**得到公鑰*/KeypublicKey=kp.getPublic();/**得到私鑰*/KeyprivateKey=kp.getPrivate();/**用對象流將生成的密鑰寫入文件*/ObjectOutputStreamoos1=newObjectOutputStream(newFileOutputStream(PUBLIC_KEY_FILE));ObjectOutputStreamoos2=newObjectOutputStream(newFileOutputStream(PRIVATE_KEY_FILE));oos1.writeObject(publicKey);oos2.writeObject(privateKey);/**清空緩存,關閉文件輸出流*/oos1.close();oos2.close();}/***生成密鑰對字符串*/privatestaticvoidgenerateKeyPairString()throwsException{/**RSA算法要求有一個可信任的隨機數(shù)源*/SecureRandomsr=newSecureRandom();/**為RSA算法創(chuàng)建一個KeyPairGenerator對象*/KeyPairGeneratorkpg=KeyPairGenerator.getInstance(ALGORITHM);/**利用上面的隨機數(shù)據(jù)源初始化這個KeyPairGenerator對象*/kpg.initialize(KEYSIZE,sr);/**生成密匙對*/KeyPairkp=kpg.generateKeyPair();/**得到公鑰*/KeypublicKey=kp.getPublic();/**得到私鑰*/KeyprivateKey=kp.getPrivate();/**用字符串將生成的密鑰寫入文件*/Stringalgorithm=publicKey.getAlgorithm();//獲取算法KeyFactorykeyFact=KeyFactory.getInstance(algorithm);BigIntegerprime=null;BigIntegerexponent=null;RSAPublicKeySpeckeySpec=(RSAPublicKeySpec)keyFact.getKeySpec(publicKey,RSAPublicKeySpec.class);prime=keySpec.getModulus();exponent=keySpec.getPublicExponent();System.out.println("公鑰模量:"+HexUtil.bytes2Hex(prime.toByteArray()));System.out.println("公鑰指數(shù):"+HexUtil.bytes2Hex(exponent.toByteArray()));System.out.println(privateKey.getAlgorithm());RSAPrivateCrtKeySpecprivateKeySpec=(RSAPrivateCrtKeySpec)keyFact.getKeySpec(privateKey,RSAPrivateCrtKeySpec.class);BigIntegerprivateModulus=privateKeySpec.getModulus();BigIntegerprivateExponent=privateKeySpec.getPrivateExponent();System.out.println("私鑰模量:"+HexUtil.bytes2Hex(privateModulus.toByteArray()));System.out.println("私鑰指數(shù):"+HexUtil.bytes2Hex(privateExponent.toByteArray()));}/***加密***source:源數(shù)據(jù)*/publicstaticStringencrypt(Stringsource)throwsException{generateKeyPair();/**將文件中的公鑰對象讀出*/ObjectInputStreamois=newObjectInputStream(newFileInputStream(PUBLIC_KEY_FILE));Keykey=(Key)ois.readObject();ois.close();Stringalgorithm=key.getAlgorithm();//獲取算法KeyFactorykeyFact=KeyFactory.getInstance(algorithm);BigIntegerprime=null;BigIntegerexponent=null;if("RSA".equals(algorithm)){//如果是RSA加密RSAPublicKeySpeckeySpec=(RSAPublicKeySpec)keyFact.getKeySpec(key,RSAPublicKeySpec.class);prime=keySpec.getModulus();exponent=keySpec.getPublicExponent();//System.out.println("公鑰模量:"+HexUtil.bytes2Hex(prime.toByteArray()));//System.out.println("公鑰指數(shù):"+HexUtil.bytes2Hex(exponent.toByteArray()));}/**得到Cipher對象來實現(xiàn)對源數(shù)據(jù)的RSA加密*/Ciphercipher=Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE,key);byte[]b=source.getBytes();/**執(zhí)行加密操作*/byte[]b1=cipher.doFinal(b);BASE64Encoderencoder=newBASE64Encoder();returnencoder.encode(b1);}/***解密算法cryptograph:密文*/publicstaticStringdecrypt(Stringcryptograph)throwsException{/**將文件中的私鑰對象讀出*/ObjectInputStreamois=newObjectInputStream(newFileInputStream(PRIVATE_KEY_FILE));Keykey=(Key)ois.readObject();Stringalgorithm=key.getAlgorithm();//獲取算法KeyFactorykeyFact=KeyFactory.getInstance(algorithm);RSAPrivateCrtKeySpecprivateKeySpec=(RSAPrivateCrtKeySpec)keyFact.getKeySpec(key,RSAPrivateCrtKeySpec.class);BigIntegerprivateModulus=privateKeySpec.getModulus();BigIntegerprivateExponent=privateKeySpec.getPrivateExponent();//System.out.println("私鑰模量:"+HexUtil.bytes2Hex(privateModulus.toByteArray()));//System.out.println("私鑰指數(shù):"+HexUtil.bytes2Hex(privateExponent.toByteArray()));/**得到Cipher對象對已用公鑰加密的數(shù)據(jù)進行RSA解密*/Ciphercipher=Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE,key);BASE64Decoderdecoder=newBASE64Decoder();byte[]b1=decoder.decodeBuffer(cryptograph);/**執(zhí)行解密操作*/byte[]b=cipher.doFinal(b1);returnnewString(b);}publicstaticvoidmain(String[]args)throwsException{generateKeyPair();//生成文件形式公鑰和私鑰//generateKeyPairString();//生成字符串形式公鑰和私鑰Stringsource="非對稱加密RSA";//要加密的字符串Stringcryptograph=encrypt(source);//生成的密文StringhexCrypt=HexUtil.bytes2Hex(cryptograph.getBytes(),false);System.out.println("生成的密文--->"+hexCrypt);Stringtarget=decrypt(HexUtil.hex2String(hexCrypt));//解密密文System.out.println("解密密文--->"+target);}}

雖然非對稱加密很安全,但是和對稱加密比起來,它非常的慢,所以我們還是要用對稱加密來傳送消息,但對稱加密所使用的密鑰我們可以通過非對稱加密的方式發(fā)送出去。

(1)對稱加密加密與解密使用的是同樣的密鑰,所以速度快,但由于需要將密鑰在網(wǎng)絡傳輸,所以安全性不高。

(2)非對稱加密使用了一對密鑰,公鑰與私鑰,所以安全性高,但加密與解密速度慢。

(3)解決的辦法是將對稱加密的密鑰使用非對稱加密的公鑰進行加密,然后發(fā)送出去,接收方使用私鑰進行解密得到對稱加密的密鑰,然后雙方可以使用對稱加密來進行溝通。

3.Base64編碼

Base64Encoding有什么用?舉個簡單的例子,你使用SMTP協(xié)議(SimpleMailTransferProtocol簡單郵件傳輸協(xié)議)來發(fā)送郵件。因為這個協(xié)議是基于文本的協(xié)議,所以如果郵件中包含一幅圖片,我們知道圖片的存儲格式是二進制數(shù)據(jù)(binarydata),而非文本格式,我們必須將二進制的數(shù)據(jù)編碼成文本格式,這時候Base64Encoding就派上用場了。

publicvoidtestJDKBase64(){StringencoderStr=java.util.Base64.getEncoder().encodeToString(s.getBytes());System.out.println("encode:"+encoderStr);StringdecodeStr=newString(java.util.Base64.getDecoder().decode(encoderStr));System.out.println("decodeStr:"+decodeStr);}publicvoidtestCodecBase64(){StringencoderStr=org.apache.commons.codec.binary.Base64.encodeBase64String(s.getBytes());System.out.println("encode:"+encoderStr);StringdecodeStr=newString(org.apache.commons.codec.binary.Base64.decodeBase64(encoderStr));System.out.println("decodeStr:"+decodeStr);}

附工具類

packagecom.hl.bluetooth.util;importorg.springframework.boot.system.ApplicationHome;importorg.springframework.stereotype.Component;importorg.springframework.web.multipart.MultipartFile;importsun.misc.BASE64Decoder;importsun.misc.BASE64Encoder;importjava.io.*;importjava.util.Objects;/***@DateL2021/11/1615:09*@ClassName:FileUtils**/@ComponentpublicclassFileUtils{publicstaticFilemultipartFileToFile(MultipartFilemultipartFile){Filefile=newFile(Objects.requireNonNull(multipartFile.getOriginalFilename()));try{InputStreamins=null;ins=multipartFile.getInputStream();OutputStreamos=newFileOutputStream(file);intbytesRead=0;byte[]buffer=newbyte[8192];while((bytesRead=ins.read(buffer,0,8192))!=-1){os.write(buffer,0,bytesRead);}os.close();ins.close();}catch(Exceptione){e.printStackTrace();}returnfile;}/***圖片轉化成base64字符串**/publicstaticStringgetImageStr(StringimgPath){InputStreamin=null;byte[]data=null;Stringencode=null;//對字節(jié)數(shù)組Base64編碼BASE64Encoderencoder=newBASE64Encoder();try{//讀取圖片字節(jié)數(shù)組in=newFileInputStream(imgPath);data=newbyte[in.available()];in.read(data);encode=encoder.encode(data);}catch(IOExceptione){e.printStackTrace();}finally{try{in.close();}catch(IOExceptione){e.printStackTrace();}}returnencode;}/***base64字符串轉化成圖片**@paramimgData圖片編碼*/publicstaticStringgenerateImage(StringimgData,StringfileName){if(imgData==null){//圖像數(shù)據(jù)為空return"null";}ApplicationHomeapplicationHome=newApplicationHome(FileUtils.class);Filesource=applicationHome.getSource();StringdirPath=source.getParentFile().toString()+"/upload";BASE64Decoderdecoder=newBASE64Decoder();Filedir=newFile(dirPath);if(!dir.exists()){dir.mkdirs();}Filefile=newFile(dirPath+"/"+fileName);if(file.exists()){file.delete();}try{//Base64解碼byte[]b=decoder.decodeBuffer(imgData);for(inti=0;i<b.length;++i){//調(diào)整異常數(shù)據(jù)if(b[i]<0){b[i]+=256;}}OutputStreamout=newFileOutputStream(dirPath+"\"+fileName);out.write(b);out.flush();out.close();returndirPath+"\"+fileName;}catch(Exceptione){e.printStackTrace();return"null";}}}

4.MD5加密

MessageDigestAlgorithmMD5(中文名為消息摘要算法第五版)為計算機安全領域廣泛使用的一種散列函數(shù),用以提供消息的完整性保護。該算法的文件號為RFC1321(R.Rivest,MITLaboratoryforComputerScienceandRSADataSecurityInc.April1992).

MD5的全稱是Message-DigestAlgorithm5(信息-摘要算法),在90年代初由MITLaboratoryforComputerScience和RSADataSecurityInc的RonaldL.Rivest開發(fā)出來,經(jīng)MD2、MD3和MD4發(fā)展而來。

MD5用于確保信息傳輸完整一致。是計算機廣泛使用的雜湊算法之一(又譯摘要算法、哈希算法),主流編程語言普遍已有MD5實現(xiàn)。將數(shù)據(jù)(如漢字)運算為另一固定長度值,是雜湊算法的基礎原理,MD5的前身有MD2、MD3和MD4。

MD5的作用是讓大容量信息在用數(shù)字簽名軟件簽署私人密鑰前被”壓縮”成一種保密的格式(就是把一個任意長度的字節(jié)串變換成一定長的十六進制數(shù)字串)。

importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;/***Java消息摘要算法MD5工具類,其實其他摘要算法的實現(xiàn)也類似*/publicclassMD5Util{/***對文本執(zhí)行md5摘要加密,此算法與mysql,JavaScript生成的md5摘要進行過一致性對比.*@paramplainText*@return返回值中的字母為小寫*/publicstaticStringmd5(StringplainText){if(null==plainText){plainText="";}StringMD5Str="";try{//JDK6支持以下6種消息摘要算法,不區(qū)分大小寫//md5,sha(sha-1),md2,sha-256,sha-384,sha-512MessageDigestmd=MessageDigest.getInstance("MD5");md.update(plainText.getBytes());byteb[]=md.digest();inti;StringBuilderbuilder=newStringBuilder(32);for(intoffset=0;offset<b.length;offset++){i=b[offset];if(i<0)i+=256;if(i<16)builder.append("0");builder.append(Integer.toHexString(i));}MD5Str=builder.toString();//LogUtil.println("result:"+buf.toString());//32位的加密}catch(NoSuchAlgorithmExceptione){e.printStackTrace();}returnMD5Str;}//一個簡版測試publicstaticvoidmain(String[]args){Stringm1=md5("1");Stringm2=md5(m1);/*輸出為*m1=c4ca4238a0b923820dcc509a6f75849b*m2=28c8edde3d61a0411511d3b1866f0636*/System.out.println("m1="+m1);System.out.println("m2="+m2);}}

通常我們不直接使用上述MD5加密。通常將MD5產(chǎn)生的字節(jié)數(shù)組交給Base64再加密一把,得到相應的字符串。

5.數(shù)字簽名算法

簽名:就有安全性,抗否認性

數(shù)字簽名:帶有密鑰(公鑰,私鑰)的消息摘要算法

作用:

1.驗證數(shù)據(jù)的完整性

2.認證數(shù)據(jù)來源

3.抗否認

數(shù)字簽名遵循:私鑰簽名,公鑰驗證

常用的數(shù)字簽名算法:RSA,DSA,ECDSA

RSA介紹:

是經(jīng)典算法,是目前為止使用最廣泛的數(shù)字簽名算法。

RSA數(shù)字簽名算法的密鑰實現(xiàn)與RSA的加密算法是一樣的,算法的名稱都叫RSA。密鑰的產(chǎn)生和轉換都是一樣的。

RSA數(shù)字簽名算法主要包括MD和SHA兩類。

importjava.security.KeyFactory;importjava.security.KeyPair;importjava.security.KeyPairGenerator;importjava.security.PrivateKey;importjava.security.PublicKey;importjava.security.Signature;importjava.security.interfaces.RSAPrivateKey;importjava.security.interfaces.RSAPublicKey;importjava.security.spec.PKCS8EncodedKeySpec;importjava.security.spec.X509EncodedKeySpec;importorg.apache.commons.codec.binary.Hex;publicclassRSATest{publicstaticfinalStringsrc="helloworld";publicstaticvoidmain(String[]args){jdkRSA();}/***說明:用java的jdk里面相關***實現(xiàn)rsa的簽名及簽名驗證*/publicstaticvoidjdkRSA(){try{//1.初始化密鑰KeyPairGeneratorkeyPairGenerator=KeyPairGenerator.getInstance("RSA");//設置KEY的長度keyPairGenerator.initialize(512);KeyPairkeyPair=keyPairGenerator.generateKeyPair();//得到公鑰RSAPublicKeyrsaPublicKey=(RSAPublicKey)keyPair.getPublic();//得到私鑰RSAPrivateKeyrsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();//2.進行簽名//用私鑰進行簽名PKCS8EncodedKeySpecpkcs8EncodedKeySpec=newPKCS8EncodedKeySpec(rsaPrivateKey.getEncoded());KeyFactorykeyFactory=KeyFactory.getInstance("RSA");//構造一個privateKeyPrivateKeyprivateKey=keyFactory.generatePrivate(pkcs8EncodedKeySpec);//聲明簽名的對象Signaturesignature=Signature.getInstance("MD5withRSA");signature.initSign(privateKey);signature.update(src.getBytes());//進行簽名byte[]result=signature.sign();System.out.println("jdkrsasign:"+Hex.encodeHexString(result));//3.驗證簽名//用公鑰進行驗證簽名X509EncodedKeySpecx509EncodedKeySpec=newX509EncodedKeySpec(rsaPublicKey.getEncoded());keyFactory=KeyFactory.getInstance("RSA");//構造一個publicKeyPublicKeypublicKey=keyFactory.generatePublic(x509EncodedKeySpec);//聲明簽名對象signature=Signature.getInstance("MD5withRSA");signature.initVerify(publicKey);signature.update(src.getBytes());//驗證簽名booleanbool=signature.verify(result);System.out.println("jdkrsaverify:"+bool);}catch(Exceptione){System.out.println(e.toString());}}}

四、應用場景

Base64應用場景:圖片轉碼(應用于郵件,img標簽,http加密)

MD5應用場景:密碼加密、imei加密、文件校驗

非對稱加密:電商訂單付款、銀行相關業(yè)務

五、附多個工具類AESpackagecom.hl.bluetooth.util;importorg.apache.commons.lang3.StringUtils;importorg.apache.tomcat.util.codec.binary.Base64;importjavax.crypto.Cipher;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;publicclassAesEncryptUtil{//使用AES-128-CBC加密模式,key需要為16位,key和iv可以相同!privatefinalstaticStringKEY="ABCDEF1234432100";privatefinalstaticStringIV="43211234DCAB6789";/***加密****@paramdata要加密的數(shù)據(jù)*@paramkey加密key*@paramiv加密iv*@return加密的結果*@throwsException*/publicstaticStringencrypt(Stringdata,Stringkey,Stringiv)throwsException{try{Ciphercipher=Cipher.getInstance("AES/CBC/NoPadding");//"算法/模式/補碼方式"NoPaddingPkcsPaddingintblockSize=cipher.getBlockSize();byte[]dataBytes=data.getBytes();intplaintextLength=dataBytes.length;if(plaintextLength%blockSize!=0){plaintextLength=plaintextLength+(blockSize-(plaintextLength%blockSize));}byte[]plaintext=newbyte[plaintextLength];System.arraycopy(dataBytes,0,plaintext,0,dataBytes.length);SecretKeySpeckeyspec=newSecretKeySpec(key.getBytes(),"AES");IvParameterSpecivspec=newIvParameterSpec(iv.getBytes());cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);byte[]encrypted=cipher.doFinal(plaintext);returnnewBase64().encodeToString(encrypted);}catch(Exceptione){e.printStackTrace();returnnull;}}/***解密****@paramdata要解密的數(shù)據(jù)*@paramkey解密key*@paramiv解密iv*@return解密的結果*@throwsException*/publicstaticStringdesEncrypt(Stringdata,Stringkey,Stringiv)throwsException{try{//byte[]encrypted1=newBase64().decode(data);byte[]encrypted1=parseHexStr2Byte(data);//Ciphercipher=Cipher.getInstance("AES/CBC/NoPadding");Ciphercipher=Cipher.getInstance("AES/CBC/PKCS5Padding");SecretKeySpeckeyspec=newSecretKeySpec(key.getBytes(),"AES");IvParameterSpecivspec=newIvParameterSpec(iv.getBytes());cipher.init(Cipher.DECRYPT_MODE,keyspec,ivspec);byte[]original=cipher.doFinal(encrypted1);StringoriginalString=newString(original);returnoriginalString;}catch(Exceptione){e.printStackTrace();returnnull;}}/***使用默認的key和iv加密*@paramdata*@return*@throwsException*/publicstaticStringencrypt(Stringdata)throwsException{returnencrypt(data,KEY,IV);}/***使用默認的key和iv解密*@paramdata*@return*@throwsException*/publicstaticStringdesEncrypt(Stringdata)throwsException{if(StringUtils.isEmpty(data)){returnnull;}returndesEncrypt(data,KEY,IV);}/***@Authorwdc*@Description16進制轉byte數(shù)組*@Date2021/4/1911:14*@Param[hexStr]*@returnbyte[]**/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;}publicstaticvoidmain(String[]args){//Stringtest="{'admin','admin'}";////Stringtest=newString(test1.getBytes(),"UTF-8");//Stringdata=null;//data=AesEncryptUtil.encrypt(test);//System.out.println("數(shù)據(jù):"+test);//System.out.println("加密:"+data);//Stringjiemi=AesEncryptUtil.desEncrypt(data);//System.out.println("解密:"+jiemi);}}base64packagecom.sgitg.util;importjava.io.UnsupportedEncodingException;importorg.springframework.util.Base64Utils;publicclassBase64Util{/***解碼base64編碼的字符串**@paramsource*@return*@throwsUnsupportedEncodingException*/publicstaticStringdecodeFromString(Stringsource){Stringstr="";try{byte[]bt=Base64Utils.decodeFromString(source);str=newString(bt,"utf-8");}catch(UnsupportedEncodingExceptione){e.printStackTrace();//TochangebodyofcatchstatementuseFile|//Settings|FileTemplates.}returnstr;}/***對字符串進行base64編碼**@paramsource*@return*@throwsUnsupportedEncodingException*/publicstaticStringencodeToString(Stringsource){byte[]bt=newbyte[0];try{bt=source.getBytes("utf-8");}catch(UnsupportedEncodingExceptione){e.printStackTrace();//TochangebodyofcatchstatementuseFile|//Settings|FileTemplates.}returnBase64Utils.encodeToString(bt);}}EncryptUtils(編碼***)*1、Base64編碼*1、AES、DES可逆算法*2、md5,Hex,Sha不可逆算法加密packagecom.sgitg.util;importorg.apache.commons.codec.digest.DigestUtils;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.nio.MappedByteBuffer;importjava.nio.channels.FileChannel;importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;importjava.security.SecureRandom;importjava.util.Base64;importjava.util.zip.CRC32;/***數(shù)據(jù)加密*繼承org.apache.commons.codec.digest.DigestUtils*1、Base64編碼*1、AES、DES可逆算法*2、md5,Hex,Sha不可逆算法加密**@authorliuyadu*/publicclassEncryptUtilsextendsDigestUtils{/***計算大文件md5獲取getMD5();SHA1獲取getSha1()CRC32獲取getCRC32()*/privatestaticchar[]hexDigits={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};//測試publicstaticvoidmain(String[]args){Stringen=encryptDES("hahahaha","yaer");Stringde=decryptDES("kzWPLLyAsDeBr84lL2COsA==","yaer");System.out.println(de);System.out.println(en);en=encryptAES("hahahaha","yaer");de=decryptAES("FBC82B89BAA1FBBDF3AE086A09D57E7C","yaer");System.out.println(de);System.out.println(en);}/***AES加密(可逆)**@paramplainText明文*@paramprivateKey密鑰*@return*@throwsNoSuchAlgorithmException*/publicstaticStringencryptAES(StringplainText,StringprivateKey){try{KeyGeneratorkgen=KeyGenerator.getInstance("AES");SecureRandomrandom=SecureRandom.getInstance("SHA1PRNG");random.setSeed(privateKey.getBytes());kgen.init(128,random);SecretKeysecretKey=kgen.generateKey();byte[]enCodeFormat=secretKey.getEncoded();SecretKeySpecsecretKeySpec=newSecretKeySpec(enCodeFormat,"AES");Ciphercipher=Cipher.getInstance("AES");byte[]byteContent=plainText.getBytes("utf-8");cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);byte[]byteRresult=cipher.doFinal(byteContent);String***=newString("");for(inti=0;i<byteRresult.length;i++){Stringhex=Integer.toHexString(byteRresult[i]&0xFF);if(hex.length()==1){hex='0'+hex;}***=***.concat(hex.toUpperCase());}return***;}catch(Exceptione){returnnull;}}/***AES解密**@paramcipherText密文*@paramprivateKey密鑰*@return*@throwsException*/publicstaticStringdecryptAES(StringcipherText,StringprivateKey){try{if(cipherText.length()<1){returnnull;}byte[]byteRresult=newbyte[cipherText.length()/2];for(inti=0;i<cipherText.length()/2;i++){inthigh=Integer.parseInt(cipherText.substring(i*2,i*2+1),16);intlow=Integer.parseInt(cipherText.substring(i*2+1,i*2+2),16);byteRresult[i]=(byte)(high*16+low);}KeyGeneratorkgen=KeyGenerator.getInstance("AES");SecureRandomrandom=SecureRandom.getInstance("SHA1PRNG");random.setSeed(privateKey.getBytes());kgen.init(128,random);SecretKeysecretKey=kgen.generateKey();byte[]enCodeFormat=secretKey.getEncoded();SecretKeySpecsecretKeySpec=newSecretKeySpec(enCodeFormat,"AES");Ciphercipher=Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);byte[]result=cipher.doFinal(byteRresult);returnnewString(result);}catch(Exceptione){returnnull;}}/***加密DES(可逆)**@paramplainText明文*@paramprivateKey密鑰*@return*/publicstaticStringencryptDES(StringplainText,StringprivateKey){try{KeyGeneratorkeygen=KeyGenerator.getInstance("DES");SecureRandomsecureRandom=SecureRandom.getInstance("SHA1PRNG");secureRandom.setSeed(privateKey.getBytes());keygen.init(56,secureRandom);SecretKeysecretKey=keygen.generateKey();Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE,secretKey);byte[]cipherBytes=cipher.doFinal(plainText.getBytes("utf-8"));byte[]plainTextBytes=Base64.getEncoder().encode(cipherBytes);returnnewString(plainTextBytes,"utf-8");}catch(Exceptione){e.printStackTrace();returnnull;}}/***解密DES**@paramcipherText密文*@paramprivateKey密鑰*@return*/publicstaticStringdecryptDES(StringcipherText,StringprivateKey){try{KeyGeneratorkeygen=KeyGenerator.getInstance("DES");SecureRandomsecureRandom=SecureRandom.getInstance("SHA1PRNG");secureRandom.setSeed(privateKey.getBytes());keygen.init(56,secureRandom);SecretKeysecretKey=keygen.generateKey();Ciphercipher=Cipher.getInstance("DES/ECB/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE,secretKey);byte[]cipherTextBytes=Base64.getDecoder().decode(cipherText.getBytes("utf-8"));byte[]cipherBytes=cipher.doFinal(cipherTextBytes);returnnewString(cipherBytes,"utf-8");}catch(Exceptione){e.printStackTrace();returnnull;}}/***獲取文件md5值**@returnmd5串*/publicstaticStringmd5(Filefile){try{//encryptMessageDigestmessagedigest=MessageDigest.getInstance("MD5");FileInputStreamin=newFileInputStream(file);FileChannelch=in.getChannel();MappedByteBufferbyteBuffer=ch.map(FileChannel.MapMode.READ_ONLY,0,file.length());messagedigest.update(byteBuffer);returnbufferToHex(messagedigest.digest());}catch(Exceptione){returnnull;}}/****獲取文件SHA1值**@returnString適用于上G大的文件*/publicstaticStringsha1(Filefile){try{MessageDigestmessagedigest=MessageDigest.getInstance("SHA-1");FileInputStreamin=newFileInputStream(file);FileChannelch=in.getChannel();MappedByteBufferbyteBuffer=ch.map(FileChannel.MapMode.READ_ONLY,0,file.length());messagedigest.update(byteBuffer);returnbufferToHex(messagedigest.digest());}catch(Exceptione){returnnull;}}/***獲取文件SHA256值**@returnString*/publicstaticStringsha256(Filefile){try{MessageDigestmessagedigest=MessageDigest.getInstance("SHA-256");FileInputStreamin=newFileInputStream(file);FileChannelch=in.getChannel();MappedByteBufferbyteBuffer=ch.map(FileChannel.MapMode.READ_ONLY,0,file.length());messagedigest.update(byteBuffer);returnbufferToHex(messagedigest.digest());}catch(Exceptione){returnnull;}}/***獲取文件CRC32碼**@returnString*/publicstaticStringcrc32(Filefile){CRC32crc32=newCRC32();//MessageDigest.getFileInputStreamfileInputStream=null;try{fileInputStream=newFileInputStream(file);byte[]buffer=newbyte[8192];intlength;while((length=fileInputStream.read(buffer))!=-1){crc32.update(buffer,0,length);}returncrc32.getValue()+"";}catch(FileNotFoundExceptione){e.printStackTrace();returnnull;}catch(IOExceptione){e.printStackTrace();returnnull;}finally{try{if(fileInputStream!=null){fileInputStream.close();}}catch(IOExceptione){e.printStackTrace();}}}/***計算二進制數(shù)據(jù)**@return*/privatestaticStringbufferToHex(bytebytes[]){returnbufferToHex(bytes,0,bytes.length);}privatestaticStringbufferToHex(bytebytes[],intm,intn){StringBufferstringbuffer=newStringBuffer(2*n);intk=m+n;for(intl=m;l<k;l++){appendHexPair(bytes[l],stringbuffer);}returnstringbuffer.toString();}privatestaticvoidappendHexPair(bytebt,StringBufferstringbuffer){charc0=hexDigits[(bt&0xf0)>>4];charc1=hexDigits[bt&0xf];stringbuffer.append(c0);stringbuffer.append(c1);}}

猜你喜歡

主站蜘蛛池模板: 国产成人精品电影 | 伊人成人在线 | 日本高清一二三区 | 在线免费黄视频 | 久久精品最新免费国产成人 | 人人干人人草 | 久久综合五月开心婷婷深深爱 | 亚洲高清中文字幕一区二区三区 | 亚洲精品98久久久久久中文字幕 | 日日操综合 | 羞羞在线视频 | 亚洲六月丁香色婷婷综合久久 | 男人天堂色男人 | 亚洲视频一区在线播放 | 深爱激情五月婷婷 | 欧美成人高清性色生活片 | 国产欧美日韩看片片在线人成 | 久久久国产99久久国产首页 | 日韩黄色在线观看 | 亚洲色图五月天 | 日韩视频网 | 欧美亚洲一区二区三区 | 日本久久久久久久 | 亚洲一区二区三区欧美 | 自拍偷拍亚洲区 | 六月丁香伊人 | 久久狠狠丁香婷婷综合 | 伊人婷婷色香五月综合缴激情 | 亚洲五月花丁香花社区 | 亚洲区精品久久一区二区三区 | 在线亚洲电影 | 狠狠亚洲婷婷综合色香 | 亚洲福利视频 | 亚洲午夜免费 | 中文字幕在线视频精品 | 亚洲最大福利 | 国内精品一区二区三区αv 国内精品久久久久不卡 | 久久综合久久精品 | 亚洲精品第五页中文字幕 | 自拍1区 | 五月天婷婷网址 |