观看麻豆影视文化有限公司-国产 高清 在线-国产 日韩 欧美 亚洲-国产 日韩 欧美 综合-日日夜夜免费精品视频-日日夜夜噜

數據加密方式(數據加密方式發展)

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

二、分類

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

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

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

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

三、算法介紹

1.對稱加密

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

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

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

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

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

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

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

下面舉個例子:

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);//創建一個密匙工廠,然后用它把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;}//從十六進制字符串到字節數組轉換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;}/***加密數據**@paramdata*待加密數據*@paramkey*密鑰*@return加密后的數據*/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());//該部分是為了與加解密在線測試網站(http://tripledes.online-domain-tools.com/)的十六進制結果進行核對for(inti=0;i<results.length;i++){System.out.print(results[i]+"");}System.out.println();//執行加密操作。加密后的結果通常都會用Base64編碼進行傳輸returnBase64.encodeBase64String(results);}/***解密數據**@paramdata*待解密數據*@paramkey*密鑰*@return解密后的數據*/publicstaticStringdecrypt(Stringdata,Stringkey)throwsException{Keydeskey=keyGenerator(key);Ciphercipher=Cipher.getInstance(CIPHER_ALGORITHM);//初始化Cipher對象,設置為解密模式cipher.init(Cipher.DECRYPT_MODE,deskey);//執行解密操作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.非對稱加密

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

目前最常用的非對稱加密算法是RSA算法,是Rivest,Shamir,和Adleman于1978年發明,他們那時都是在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算法要求有一個可信任的隨機數源*/SecureRandomsr=newSecureRandom();/**為RSA算法創建一個KeyPairGenerator對象*/KeyPairGeneratorkpg=KeyPairGenerator.getInstance(ALGORITHM);/**利用上面的隨機數據源初始化這個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算法要求有一個可信任的隨機數源*/SecureRandomsr=newSecureRandom();/**為RSA算法創建一個KeyPairGenerator對象*/KeyPairGeneratorkpg=KeyPairGenerator.getInstance(ALGORITHM);/**利用上面的隨機數據源初始化這個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("公鑰指數:"+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("私鑰指數:"+HexUtil.bytes2Hex(privateExponent.toByteArray()));}/***加密***source:源數據*/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("公鑰指數:"+HexUtil.bytes2Hex(exponent.toByteArray()));}/**得到Cipher對象來實現對源數據的RSA加密*/Ciphercipher=Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE,key);byte[]b=source.getBytes();/**執行加密操作*/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("私鑰指數:"+HexUtil.bytes2Hex(privateExponent.toByteArray()));/**得到Cipher對象對已用公鑰加密的數據進行RSA解密*/Ciphercipher=Cipher.getInstance(ALGORITHM);cipher.init(Cipher.DECRYPT_MODE,key);BASE64Decoderdecoder=newBASE64Decoder();byte[]b1=decoder.decodeBuffer(cryptograph);/**執行解密操作*/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);}}

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

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

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

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

3.Base64編碼

Base64Encoding有什么用?舉個簡單的例子,你使用SMTP協議(SimpleMailTransferProtocol簡單郵件傳輸協議)來發送郵件。因為這個協議是基于文本的協議,所以如果郵件中包含一幅圖片,我們知道圖片的存儲格式是二進制數據(binarydata),而非文本格式,我們必須將二進制的數據編碼成文本格式,這時候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;//對字節數組Base64編碼BASE64Encoderencoder=newBASE64Encoder();try{//讀取圖片字節數組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){//圖像數據為空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){//調整異常數據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(中文名為消息摘要算法第五版)為計算機安全領域廣泛使用的一種散列函數,用以提供消息的完整性保護。該算法的文件號為RFC1321(R.Rivest,MITLaboratoryforComputerScienceandRSADataSecurityInc.April1992).

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

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

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

importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;/***Java消息摘要算法MD5工具類,其實其他摘要算法的實現也類似*/publicclassMD5Util{/***對文本執行md5摘要加密,此算法與mysql,JavaScript生成的md5摘要進行過一致性對比.*@paramplainText*@return返回值中的字母為小寫*/publicstaticStringmd5(StringplainText){if(null==plainText){plainText="";}StringMD5Str="";try{//JDK6支持以下6種消息摘要算法,不區分大小寫//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產生的字節數組交給Base64再加密一把,得到相應的字符串。

5.數字簽名算法

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

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

作用:

1.驗證數據的完整性

2.認證數據來源

3.抗否認

數字簽名遵循:私鑰簽名,公鑰驗證

常用的數字簽名算法:RSA,DSA,ECDSA

RSA介紹:

是經典算法,是目前為止使用最廣泛的數字簽名算法。

RSA數字簽名算法的密鑰實現與RSA的加密算法是一樣的,算法的名稱都叫RSA。密鑰的產生和轉換都是一樣的。

RSA數字簽名算法主要包括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里面相關***實現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加密、文件校驗

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

五、附多個工具類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要加密的數據*@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要解密的數據*@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數組*@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("數據:"+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;/***數據加密*繼承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();}}}/***計算二進制數據**@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);}}

猜你喜歡

主站蜘蛛池模板: 男人的天堂久久精品激情 | 日韩二区三区 | 亚洲天堂久久久 | 九九九九视频 | 一级国产精品一级国产精品片 | 香蕉香蕉国产片一级一级毛片 | 日本三级成人中文字幕乱码 | 国产福利久久 | 草草国产成人免费视频 | 亚洲综合成人网在线观看 | 欧美日韩午夜视频 | 男人躁女人躁的好爽免费视频 | 男人精品一线视频在线观看 | 国产aⅴ一区二区 | 国产一级精品毛片 | 久久综合狠狠综合久久综合88 | 毛片免费视频网站 | 精品日韩一区二区三区视频 | 国产一区二区三区免费 | 成人综合婷婷国产精品久久免费 | 欧美日一区 | 亚洲黄色软件 | 日韩欧美在线精品 | 深夜福利视频在线看免费 | 91成人在线视频 | 国产欧美日韩精品一区二区三区 | 日韩在线视频免费不卡一区 | 在线视频 亚洲 | 国产a级一级久久毛片 | 久久免费看视频 | 久久精品国产只有精品6 | 亚洲网美女 | 国产视频二 | 2022年国产精品久久久久 | 日本三级香港三级人妇gg在线 | 国产成人精品女人不卡在线 | 特级毛片永久久免费观看 | 日本一级特大毛片 | 清纯偷拍精品视频在线观看 | 欧美视频一 | 国产一区二区三区视频在线观看 |