有哪些網(wǎng)站做汽車周邊服務(wù)360手機優(yōu)化大師下載
RSA非對稱加密解密,前端公鑰加密后端私鑰解密,可以防止陌生人直接通過后端接口篡改數(shù)據(jù)。有數(shù)據(jù)泄露的風(fēng)險。
前端:Vue框架
后端:sprintboot(Java)
工具類:hutool
前端Vue獲取公鑰:
這里安裝jsencrypt這個庫進行RSA的加密
npm i jsencrypt --force
通過后端接口getJSEncryptPublic獲取公鑰之后,直接套函數(shù)加密
/*** 前端vue公鑰加密,后段私鑰解密* @return*/@GetMapping("/getJSEncryptPublic")public String getJSEncryptPublic(){String str = (String)stringRedisTemplate.opsForValue().get("privateKey");if (StringUtils.isNotBlank(str)){stringRedisTemplate.delete("privateKey");}Map<String, String> mapKeyPair = getMapKeyPair();this.privateKey = mapKeyPair.get("privateKey");stringRedisTemplate.opsForValue().set("privateKey",this.privateKey,15, TimeUnit.MINUTES);this.publicKey = mapKeyPair.get("publicKey");return this.publicKey;}
/*** 獲取私鑰,公鑰* @return*/public static Map<String,String> getMapKeyPair() {
// String privateKey = bytesToBase64(getRsaKey().getPrivate().getEncoded());
// String publicKey = bytesToBase64(getRsaKey().getPublic().getEncoded());// 生成對象,包含鑰匙一對RSA rsa = new RSA();// 提取公鑰并轉(zhuǎn)成base64編碼String publicKeyBase64 = rsa.getPublicKeyBase64();// 提取私鑰并轉(zhuǎn)成base64編碼String privateKeyBase64 = rsa.getPrivateKeyBase64();Map<String,String> map = new HashMap<>();//privateKey 私鑰map.put("privateKey",privateKeyBase64);//publicKey 公鑰map.put("publicKey",publicKeyBase64);return map;}
import JSEncrypt from 'jsencrypt/bin/jsencrypt';axios.get('http://localhost:8887/jing/Xqy/user/getJSEncryptPublic').then(reponse =>{console.log("加密加密:",reponse.data);const publicKey = reponse.data // 提取公鑰// 獲取密碼對象const encryptor = new JSEncrypt()// 放入公鑰encryptor.setPublicKey(publicKey) // 放入加密的內(nèi)容,并加密this.passByPublicKey = encryptor.encrypt(this.ruleFormLogin.pass) // 加密后的密文console.log("passByPublicKey:"+this.passByPublicKey) //調(diào)用queryzhuce()傳密文
之后在以密文的形式傳給后端(這里調(diào)用登錄接口queryzhuce()方法),然后后端利用私鑰解密獲取到真正的明文。
后端獲取密文并解密:
如下此時pass是加密后的密文
@GetMapping("/queryZhuce")public List<CaiwuUser> queryZhuce(@RequestParam(name = "username",required = false)String username,@RequestParam(name = "pass",required = false)String pass,HttpServletRequest request){//解密String decyptByRSAPass = getDecyptByRSA(pass, this.privateKey, this.publicKey);System.out.println("decyptByRSAPass:"+decyptByRSAPass);return xqyService.queryZhuce(username,decyptByRSAPass,request);}
/*** 私鑰解密* @param rsaPass* @param privateKey* @return*/public static String getDecyptByRSA(String rsaPass,String privateKey,String publicKeyStr){RSA rsa = new RSA(privateKey, null);String s = rsa.decryptStr(rsaPass, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);//String s = new String(decrypt, CharsetUtil.CHARSET_UTF_8);return s;}
RSA非對稱加密公共類
RSAUtil類:
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.alibaba.fastjson.JSON;
import com.richfit.richfit.dto.AllDataDto;import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;/*** RSA加密解密驗簽*/
public class RSAUtil {/*** 獲取私鑰,公鑰* @return*/public static Map<String,String> getMapKeyPair() {
// String privateKey = bytesToBase64(getRsaKey().getPrivate().getEncoded());
// String publicKey = bytesToBase64(getRsaKey().getPublic().getEncoded());// 生成對象,包含鑰匙一對RSA rsa = new RSA();// 提取公鑰并轉(zhuǎn)成base64編碼String publicKeyBase64 = rsa.getPublicKeyBase64();// 提取私鑰并轉(zhuǎn)成base64編碼String privateKeyBase64 = rsa.getPrivateKeyBase64();Map<String,String> map = new HashMap<>();map.put("privateKey",privateKeyBase64);map.put("publicKey",publicKeyBase64);return map;}public static void main(String[] args) {Map<String, String> mapKeyPair = getMapKeyPair();AllDataDto allDataDto = new AllDataDto(null,mapKeyPair.get("privateKey"),mapKeyPair.get("publicKey"),null);System.out.println(JSON.toJSONString(allDataDto));}/*** 私鑰解密* @param rsaPass* @param privateKey* @return*/public static String getDecyptByRSA(String rsaPass,String privateKey,String publicKeyStr){RSA rsa = new RSA(privateKey, null);String s = rsa.decryptStr(rsaPass, KeyType.PrivateKey, CharsetUtil.CHARSET_UTF_8);//String s = new String(decrypt, CharsetUtil.CHARSET_UTF_8);return s;}/*** 生成私鑰和公鑰* @return*/public static KeyPair getRsaKey(){//生成RSA私鑰KeyPair pair = SecureUtil.generateKeyPair("RSA");return pair;}/*** 生成私鑰* @return*/public static String getRsaPrivateKey(){//生成RSA私鑰KeyPair pair = SecureUtil.generateKeyPair("RSA");PrivateKey privateKey = pair.getPrivate();return bytesToBase64(privateKey.getEncoded());}/*** 生成公鑰* @return*/public static String getRsaPublicKey(){//生成RSA私鑰KeyPair pair = SecureUtil.generateKeyPair("RSA");PrivateKey privateKey = pair.getPrivate();return bytesToBase64(privateKey.getEncoded());}/*** 根據(jù)入?yún)⑸晒€,私鑰,驗簽* @param text* @return*/public static AllDataDto getAllRsaObject(String text){if (StrUtil.isBlank(text)){throw new RuntimeException("參數(shù)不能為空!");}text = text.trim();Map<String,String> map = getMapKeyPair();Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, map.get("privateKey"), map.get("publicKey"));//簽名byte[] data = text.getBytes(StandardCharsets.UTF_8);byte[] signed = sign.sign(data);String signedStr = bytesToBase64(signed);System.out.println("簽名:" + signedStr);//驗證簽名boolean verify = sign.verify(data, base64ToBytes(signedStr));System.out.println("驗簽:" + verify);AllDataDto allDataDto = new AllDataDto(signedStr, map.get("privateKey"), map.get("publicKey"), text);System.out.println("allDataDto:" + JSON.toJSON(allDataDto));return allDataDto;}// public static void main(String[] args) {
// Map<String, String> map = getMapKeyPair();
// String sign = getSign("123",map.get("privateKey"),map.get("publicKey"));
// System.out.println("簽名:"+sign);
// }// public static void main(String[] args) {
// String text = "人最寶貴的是生命.生命對每個人只有一次.人的一生應(yīng)當(dāng)這樣度過:當(dāng)他回首往事的時候,不會因為虛度年華而悔恨,也不會因為碌碌無為而羞恥.這樣,在臨死的時候,他能夠說:“我已把自己的整個的生命和全部的精力獻給了世界上最壯麗的事業(yè)---------為人類的解放而斗爭.”";
// System.out.println("原文:" + text);
//
// //生成公私鑰對
// KeyPair pair = SecureUtil.generateKeyPair("RSA");
// PrivateKey privateKey = pair.getPrivate();
// PublicKey publicKey = pair.getPublic();
// //獲得私鑰
// String privateKeyStr = bytesToBase64(privateKey.getEncoded());
// System.out.println("私鑰:" + privateKeyStr);
// //獲得公鑰
// String publicKeyStr = bytesToBase64(publicKey.getEncoded());
// System.out.println("公鑰:" + publicKeyStr);
//
// RSA rsa = new RSA(privateKeyStr, publicKeyStr);
// System.out.println(rsa);
//
// //公鑰加密,私鑰解密
// byte[] encrypt = rsa.encrypt(StrUtil.bytes(text, CharsetUtil.CHARSET_UTF_8), KeyType.PublicKey);
// System.out.println("公鑰加密:" + bytesToBase64(encrypt));
//
// byte[] decrypt = rsa.decrypt(encrypt, KeyType.PrivateKey);
// System.out.println("私鑰解密:" + new String(decrypt,StandardCharsets.UTF_8));
////私鑰加密,公鑰解密byte[] encrypt2 = rsa.encrypt(StrUtil.bytes(text, CharsetUtil.CHARSET_UTF_8), KeyType.PrivateKey);System.out.println("私鑰加密:" + bytesToBase64(encrypt2));byte[] decrypt2 = rsa.decrypt(encrypt2, KeyType.PublicKey);System.out.println("公鑰解密:" + bytesToBase64(decrypt2));
//
// Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKeyStr, publicKeyStr);
// //簽名
// byte[] data = text.getBytes(StandardCharsets.UTF_8);
// byte[] signed = sign.sign(data);
// String signedStr = bytesToBase64(signed);
// System.out.println("簽名:" + signedStr);
//
// //驗證簽名
// boolean verify = sign.verify(data, base64ToBytes(signedStr));
// System.out.println("驗簽:" + verify);
//
// }/*** 驗證簽名* @param text 入?yún)? @param signedStr 簽名* @param privateKeyStr 私鑰* @param publicKeyStr 公鑰* @return 簽名是否合法*/public static Boolean verifySign(String text,String signedStr,String privateKeyStr,String publicKeyStr){Sign sign = SecureUtil.sign(SignAlgorithm.SHA256withRSA, privateKeyStr, publicKeyStr);//驗證簽名boolean verify = sign.verify(text.getBytes(StandardCharsets.UTF_8), base64ToBytes(signedStr));System.out.println("驗簽:" + verify);return verify;}/*** 字節(jié)數(shù)組轉(zhuǎn)Base64編碼** @param bytes 字節(jié)數(shù)組* @return Base64編碼*/private static String bytesToBase64(byte[] bytes) {byte[] encodedBytes = Base64.getEncoder().encode(bytes);return new String(encodedBytes, StandardCharsets.UTF_8);}/*** Base64編碼轉(zhuǎn)字節(jié)數(shù)組** @param base64Str Base64編碼* @return 字節(jié)數(shù)組*/private static byte[] base64ToBytes(String base64Str) {byte[] bytes = base64Str.getBytes(StandardCharsets.UTF_8);return Base64.getDecoder().decode(bytes);}
}