文章詳情頁
vue前端RSA加密java后端解密的方法實現
瀏覽:73日期:2022-06-01 17:02:33
目錄
- 一、前言
- 二、前端代碼與用法
- 三、后端代碼與用法
一、前言
最近安全測試的總是測出安全漏洞來,讓開發改。
想了想干脆把請求參數都加密下,前端加密后端解密,這樣總差不多了。
看了下AES加密,是對稱的,前后端用這個不太行。
于是想到用RSA加密,是非對稱的,可以前端加密后端解密。
二、前端代碼與用法
1.前端是vue項目,使用時,需要先執行:
npm i jsencrypt
把這個依賴下載到node_modules里面。
2.可以增加一個工具類文件:項目名/src/utils/commonUtil.js,內容如下:
import JSEncrypt from "jsencrypt"; export default { ? encodeRSA(word, keyStr) { ? ? //這個是公鑰,有入參時用入參,沒有入參用默認公鑰 ? ? keyStr = keyStr ? keyStr : "MIGxxxxxxxxxxxxxxxxxxxxxxxxxx"; ? ? //創建對象 ? ? const jsRsa = new JSEncrypt(); ? ? //設置公鑰 ? ? jsRsa.setPublicKey(keyStr); ? ? //返回加密后結果 ? ? return jsRsa.encrypt(word); ? } }
3.然后,需要使用的地方,就可以這樣用:
//引入第2步的工具類 import commonUtil from "@utils/commonUtil" //引入一個發請求的方法,這個也需要npm i import axios from "axios" //一個發請求用的方法 export function myget(userId) { ? return axios.get(`/xxx/user`, { ? ? headers: { ? ? ? //先把參數rsa加密下,再用urlEncoder轉下碼,然后放header里傳給后臺 ? ? ? userId: encodeURIComponent(commonUtil.encodeRSA(userId, null)), ? ? }, ? }).then(res => { ? ? return res.data ? }) }
這樣,就把加密參數放入header里的userId里了,后臺可以取出后解密。
三、后端代碼與用法
1.可以先寫個工具類,如下:(RSA公鑰和私鑰可以用這個工具類生成,然后自己記錄后使用)
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import javax.crypto.Cipher; import java.security.KeyFactory; import java.security.Security; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Map; import java.util.HashMap; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.KeyPair; public class RSAUtil { ? ? //公鑰,可以寫前端 ? ? public static String public_key="MIGxxxxxx"; ? ? //私鑰,只能放后端 ? ? public static String private_key="MIICxxxxxxxx"; ? ? public static void main(String[] args) { ? ? ? ? //解密數據 ? ? ? ? try { ? ? ? ? ? ? //生成公鑰和私鑰 ? ? ? ? ? ? genKeyPair(); ? ? ? ? ? ? String publicKey = keyMap.get(0); ? ? ? ? ? ? //打印出來自己記錄下 ? ? ? ? ? ? System.out.println("公鑰:" + publicKey); ? ? ? ? ? ? String privateKey = keyMap.get(1); ? ? ? ? ? ? //打印出來自己記錄下 ? ? ? ? ? ? System.out.println("私鑰:" + privateKey); ? ? ? ? ? ? //獲取到后,可以放這里,測試下能不能正確加解密 ? ? ? ? ? ? publicKey = public_key; ? ? ? ? ? ? privateKey = private_key; ? ? ? ? ? ? String orgData = "test"; ? ? ? ? ? ? System.out.println("原數據:" + orgData); ? ? ? ? ? ?? ? ? ? ? ? ? //加密 ? ? ? ? ? ? String encryptStr =encrypt(orgData,publicKey); ? ? ? ? ? ? System.out.println("加密結果:" + encryptStr); ? ? ? ? ? ? //解密 ? ? ? ? ? ? String decryptStr = decrypt(encryptStr,privateKey); ? ? ? ? ? ? System.out.println("解密結果:" + decryptStr); ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? e.printStackTrace(); ? ? ? ? } ? ? } ? ? /** ? ? ?* RSA公鑰加密 ? ? ?* ? ? ?* @param str ? ? ? 加密字符串 ? ? ?* @param publicKey 公鑰 ? ? ?* @return 密文 ? ? ?* @throws Exception 加密過程中的異常信息 ? ? ?*/ ? ? public static String encrypt(String str,String publicKey) throws Exception { ? ? ? ? //base64編碼的公鑰 ? ? ? ? byte[] decoded = decryptBASE64(publicKey); ? ? ? ? Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); ? ? ? ? RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded)); ? ? ? ? //RSA加密 ? ? ? ? Cipher cipher = Cipher.getInstance("RSA"); ? ? ? ? cipher.init(Cipher.ENCRYPT_MODE, pubKey); ? ? ? ? String outStr = encryptBASE64(cipher.doFinal(str.getBytes("UTF-8"))); ? ? ? ? return outStr; ? ? } ? ? /** ? ? ?* RSA私鑰解密 ? ? ?* ? ? ?* @param str ? ? ? ?加密字符串 ? ? ?* @param privateKey 私鑰 ? ? ?* @return 明文 ? ? ?* @throws Exception 解密過程中的異常信息 ? ? ?*/ ? ? public static String decrypt(String str, String privateKey) throws Exception { ? ? ? ? //64位解碼加密后的字符串 ? ? ? ? byte[] inputByte = decryptBASE64(str); ? ? ? ? //base64編碼的私鑰 ? ? ? ? byte[] decoded = decryptBASE64(privateKey); ? ? ? ? Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); ? ? ? ? RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded)); ? ? ? ? //RSA解密 ? ? ? ? Cipher cipher = Cipher.getInstance("RSA"); ? ? ? ? cipher.init(Cipher.DECRYPT_MODE, priKey); ? ? ? ? String outStr = new String(cipher.doFinal(inputByte)); ? ? ? ? return outStr; ? ? } ? ? //編碼返回字符串 ? ? public static String encryptBASE64(byte[] key) throws Exception { ? ? ? ? return (new BASE64Encoder()).encodeBuffer(key); ? ? } ? ? //解碼返回byte ? ? public static byte[] decryptBASE64(String key) throws Exception { ? ? ? ? return (new BASE64Decoder()).decodeBuffer(key); ? ? } ? ? /** ? ? ?* 密鑰長度 于原文長度對應 以及越長速度越慢 ? ? ?*/ ? ? private final static int KEY_SIZE = 1024; ? ? /** ? ? ?* 用于封裝隨機產生的公鑰與私鑰 ? ? ?*/ ? ? private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); ? ? /** ? ? ?* 隨機生成密鑰對 ? ? ?* @throws Exception ? ? ?*/ ? ? public static void genKeyPair() throws Exception { ? ? ? ? // KeyPairGenerator類用于生成公鑰和私鑰對,基于RSA算法生成對象 ? ? ? ? KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); ? ? ? ? // 初始化密鑰對生成器 ? ? ? ? keyPairGen.initialize(KEY_SIZE, new SecureRandom()); ? ? ? ? // 生成一個密鑰對,保存在keyPair中 ? ? ? ? KeyPair keyPair = keyPairGen.generateKeyPair(); ? ? ? ? // 得到私鑰 ? ? ? ? RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); ? ? ? ? // 得到公鑰 ? ? ? ? RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); ? ? ? ? String publicKeyString = encryptBASE64(publicKey.getEncoded()); ? ? ? ? // 得到私鑰字符串 ? ? ? ? String privateKeyString = encryptBASE64(privateKey.getEncoded()); ? ? ? ? // 將公鑰和私鑰保存到Map ? ? ? ? //0表示公鑰 ? ? ? ? keyMap.put(0, publicKeyString); ? ? ? ? //1表示私鑰 ? ? ? ? keyMap.put(1, privateKeyString); ? ? } }
2.使用時,把公鑰內容放入前端js,私鑰內容就放后端代碼里,就可以和前端聯調測試了。樣例如下:
? ? //測試接口 ? ? @GetMapping("/xxx/user") ? ? public String myget(HttpServletRequest request) { ? ? ? ? //先用非對稱算法RSA解密一下 ? ? ? ? try { ? ? ? ? ? ? //從header里獲取到參數 ? ? ? ? ? ? String userId = request.getHeader("userId"); ? ? ? ? ? ? log.debug("收到userId,內容為:"+userId); ? ? ? ? ? //這里解密,注意先用URLDecode處理了下,如果前端沒有用的話,這里也不用處理 ? ? ? ? ? ? userId = RSAUtil.decrypt(URLDecoder.decode(userId,"UTF-8"), RSAUtil.private_key); ? ? ? ? ? ? log.debug("RSA解密成功,userId為"+userId); ? ? ? ? ? ?? ? ? ? ? } catch (Exception e) { ? ? ? ? ? ? log.error("RSA解密失敗",e); ? ? ? ? ? ? //如果解密失敗,就返回null ? ? ? ? ? ? return null; ? ? ? ? } ? ? ? ? return "成功"; ? ? }
到此這篇關于vue前端RSA加密java后端解密的方法實現的文章就介紹到這了,更多相關vue RSA加密java后端解密內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
標簽:
JavaScript
排行榜
