Java实现AES和RSA算法
生活随笔
收集整理的這篇文章主要介紹了
Java实现AES和RSA算法
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
說明:
本文是用 Java1.8 官方的工具類進(jìn)行的封裝,兩種加密算法的原理參考:
AES:https://blog.csdn.net/gulang03/article/details/81175854
RSA:https://blog.csdn.net/gulang03/article/details/81176133
實(shí)現(xiàn)類:
? AESUtil:
package com.fknight.sbsmdemo.tools;import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64;/*** AES 加密方法,是對(duì)稱的密碼算法(加密與解密的密鑰一致),這里使用最大的 256 位的密鑰*/ public class AESUtil {/*** 獲得一個(gè) 密鑰長度為 256 位的 AES 密鑰,* @return 返回經(jīng) BASE64 處理之后的密鑰字符串*/public static String getStrKeyAES() throws NoSuchAlgorithmException, UnsupportedEncodingException {KeyGenerator keyGen = KeyGenerator.getInstance("AES");SecureRandom secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes("utf-8"));keyGen.init(256, secureRandom); // 這里可以是 128、192、256、越大越安全SecretKey secretKey = keyGen.generateKey();return Base64.getEncoder().encodeToString(secretKey.getEncoded());}/*** 將使用 Base64 加密后的字符串類型的 secretKey 轉(zhuǎn)為 SecretKey* @param strKey* @return SecretKey*/public static SecretKey strKey2SecretKey(String strKey){byte[] bytes = Base64.getDecoder().decode(strKey);SecretKeySpec secretKey = new SecretKeySpec(bytes, "AES");return secretKey;}/*** 加密* @param content 待加密內(nèi)容* @param secretKey 加密使用的 AES 密鑰* @return 加密后的密文 byte[]*/public static byte[] encryptAES(byte[] content, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, secretKey);return cipher.doFinal(content);}/*** 解密* @param content 待解密內(nèi)容* @param secretKey 解密使用的 AES 密鑰* @return 解密后的明文 byte[]*/public static byte[] decryptAES(byte[] content, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE, secretKey);return cipher.doFinal(content);} }? RSAUtil:
package com.fknight.sbsmdemo.tools;import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64;/*** RSA 是非對(duì)稱的密碼算法,密鑰分公鑰和私鑰,公鑰用來加密,私鑰用于解密*/public class RSAUtil {/*** 生成密鑰對(duì):密鑰對(duì)中包含公鑰和私鑰* @return 包含 RSA 公鑰與私鑰的 keyPair* @throws NoSuchAlgorithmException* @throws UnsupportedEncodingException*/public static KeyPair getKeyPair() throws NoSuchAlgorithmException, UnsupportedEncodingException {KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); // 獲得RSA密鑰對(duì)的生成器實(shí)例SecureRandom secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes("utf-8")); // 說的一個(gè)安全的隨機(jī)數(shù)keyPairGenerator.initialize(2048, secureRandom); // 這里可以是1024、2048 初始化一個(gè)密鑰對(duì)KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 獲得密鑰對(duì)return keyPair;}/*** 獲取公鑰 (并進(jìn)行Base64編碼,返回一個(gè) Base64 編碼后的字符串)* @param keyPair* @return 返回一個(gè) Base64 編碼后的公鑰字符串*/public static String getPublicKey(KeyPair keyPair){PublicKey publicKey = keyPair.getPublic();byte[] bytes = publicKey.getEncoded();return Base64.getEncoder().encodeToString(bytes);}/*** 獲取私鑰(并進(jìn)行Base64編碼,返回一個(gè) Base64 編碼后的字符串)* @param keyPair* @return 返回一個(gè) Base64 編碼后的私鑰字符串*/public static String getPrivateKey(KeyPair keyPair){PrivateKey privateKey = keyPair.getPrivate();byte[] bytes = privateKey.getEncoded();return Base64.getEncoder().encodeToString(bytes);}/*** 將Base64編碼后的公鑰轉(zhuǎn)換成 PublicKey 對(duì)象* @param pubStr* @return PublicKey*/public static PublicKey string2PublicKey(String pubStr) throws NoSuchAlgorithmException, InvalidKeySpecException {byte[] bytes = Base64.getDecoder().decode(pubStr);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/*** 將Base64編碼后的私鑰轉(zhuǎn)換成 PrivateKey 對(duì)象* @param priStr* @return PrivateKey*/public static PrivateKey string2Privatekey(String priStr) throws NoSuchAlgorithmException, InvalidKeySpecException {byte[] bytes = Base64.getDecoder().decode(priStr);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/*** 公鑰加密* @param content 待加密的內(nèi)容 byte[]* @param publicKey 加密所需的公鑰對(duì)象 PublicKey* @return 加密后的字節(jié)數(shù)組 byte[]*/public static byte[] publicEncrytype(byte[] content, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] bytes = cipher.doFinal(content);return bytes;}/*** 私鑰解密* @param content 待解密的內(nèi)容 byte[]* @param privateKey 解密需要的私鑰對(duì)象 PrivateKey* @return 解密后的字節(jié)數(shù)組 byte[]*/public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] bytes = cipher.doFinal(content);return bytes;} }測試:
AESUtilTest
package com.fknight.sbsmdemo.tools;import javax.crypto.SecretKey; import java.util.Base64;/*** 測試 AESUtil 對(duì)AES加密算法的封裝*/ public class AESUtilTest {public static void main(String[] args){String content = "abcdefg789+-*+="; // 待加密的字符串System.out.println("明文數(shù)據(jù)為:" + content);try {// 獲得經(jīng) BASE64 處理之后的 AES 密鑰String strKeyAES = AESUtil.getStrKeyAES();System.out.println("經(jīng)BASE64處理之后的密鑰:" + strKeyAES);// 將 BASE64 處理之后的 AES 密鑰轉(zhuǎn)為 SecretKeySecretKey secretKey = AESUtil.strKey2SecretKey(strKeyAES);// 加密數(shù)據(jù)byte[] encryptAESbytes = AESUtil.encryptAES(content.getBytes("utf-8"), secretKey);System.out.println("加密后的數(shù)據(jù)經(jīng) BASE64 處理之后為:" + Base64.getEncoder().encodeToString(encryptAESbytes));// 解密數(shù)據(jù)String decryptAESStr = new String(AESUtil.decryptAES(encryptAESbytes, secretKey), "utf-8");System.out.println("解密后的數(shù)據(jù)為:" + decryptAESStr);if (content.equals(decryptAESStr)){System.out.println("測試通過!");}else {System.out.println("測試未通過!");}} catch (Exception e) {e.printStackTrace();}} }測試結(jié)果:
RSAUtilTest
package com.fknight.sbsmdemo.tools;import java.security.*; import java.util.Base64;/*** 對(duì) RSAUtil 進(jìn)行測試*/ public class RSAUtilTest {public static void main(String[] args){String content = "abcdefg456+-="; // 明文內(nèi)容System.out.println("原始字符串是:" + content);try {// 獲得密鑰對(duì)KeyPair keyPair = RSAUtil.getKeyPair();// 獲得進(jìn)行Base64 加密后的公鑰和私鑰 StringString privateKeyStr = RSAUtil.getPrivateKey(keyPair);String publicKeyStr = RSAUtil.getPublicKey(keyPair);System.out.println("Base64處理后的私鑰:" + privateKeyStr + "\n"+ "Base64處理后的公鑰:" + publicKeyStr);// 獲得原始的公鑰和私鑰,并以字符串形式打印出來PrivateKey privateKey = RSAUtil.string2Privatekey(privateKeyStr);PublicKey publicKey = RSAUtil.string2PublicKey(publicKeyStr);// 公鑰加密/私鑰解密byte[] publicEncryBytes = RSAUtil.publicEncrytype(content.getBytes(), publicKey);System.out.println("公鑰加密后的字符串(經(jīng)BASE64處理):" + Base64.getEncoder().encodeToString(publicEncryBytes));byte[] privateDecryBytes = RSAUtil.privateDecrypt(publicEncryBytes, privateKey);System.out.println("私鑰解密后的原始字符串:" + new String(privateDecryBytes));String privateDecryStr = new String(privateDecryBytes, "utf-8");if (content.equals(privateDecryStr)){System.out.println("測試通過!");}else {System.out.println("測試未通過!");}} catch (Exception e) {e.printStackTrace();}} }測試結(jié)果:
PS:關(guān)于如何使用 JavaScript 和 Java 進(jìn)行跨語言 AES 和 RSA 的實(shí)現(xiàn)可以參考我的另一篇博文
https://blog.csdn.net/gulang03/article/details/82230408
總結(jié)
以上是生活随笔為你收集整理的Java实现AES和RSA算法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis分页插件PageHelpe
- 下一篇: 修改 cmd 控制台默认代码页编码的几种