公钥与私钥机制属于非对称加密的范畴,非对称是相对于对称加密而言的,对称加密用于加密与解密的密钥是同一把,而非对称加密则用于加密与解密的密钥不相同,一个公开,称为公钥;一个保密,称为私钥,公钥与私钥必须成对出现,只有是配对的公钥与私钥才能用于加解密。公钥通过非安全通道发放,私钥则由发放者保留,公钥加密的数据,只能使用其配对的私钥对其解密;反之,私钥加密的数据,只可使用公钥对其解密。
一、 什么是RSA加密?
RSA是一种使用不同的加密密钥与解密密钥的体制,不对称加密算法。公钥加密,私钥解密。
RSA算法是先生成一对RSA密钥,其中之一是保密密钥,由用户保存;另一个为公开密钥,可对外公开,甚至可在网络服务器中注册。为提高保密强度,一般推荐使用1024位。
二、引入jsencrypt.js文件
CDN下载或引用js
https://www.bootcdn.cn/jsencrypt/
<script src="https://cdn.bootcdn.net/ajax/libs/jsencrypt/3.2.1/jsencrypt.min.js"></script>
三、生成公钥和私钥
RSA加密解密需要用到公钥和私钥,可以在这个网站生成
http://web.chacuo.net/netrsakeypair
公钥在外部使用,私钥在系统内部使用,生成后妥善保管
四、使用
-
将下载好的jsencrypt.js放在一个专门的文件夹,例如 utils/jsencrypt.js
-
为了方便使用,在同一目录下新建文件 rsa.js:
import { JSEncrypt } from './jsencrypt'
const key = `---`
export function rsaEncrypt (msg) {
const jsencrypt = new JSEncrypt()
jsencrypt.setPublicKey(key)
const encryptMsg = jsencrypt.encrypt(msg)
return encryptMsg
}
const privateKey = `---`
export function rsaDecrypt (msg) {
const decrypt = new JSEncrypt()
decrypt.setPrivateKey(privateKey)
const decryptMsg = decrypt.decrypt(msg)
return decryptMsg
}
- 在第二步已经导出了加密(rsaEncrypt)和 解密(rsaDecrypt)的方法,在需要用到的地方导入使用即可。
import { rsaEncrypt, rsaDecrypt } from '@/utils/rsa'
let msg = '我是被传输的重要明文信息哈哈哈哈哈'
let encryptMsg = rsaEncrypt(msg)
console.log(encryptMsg )
let decryptMsg = rsaDecrypt(encryptMsg)
console.log(decryptMsg)
五、也可以在java中加密解密
请参考
https://blog.csdn.net/weixin_45740811/article/details/124344674
核心解密代码如下
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
public class EncryptUtil {
public static String encrypt(String text,String publicKeyStr) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyStr));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.getEncoder().encodeToString(result);
}
参考文章
前端使用jsencrypt进行RSA加密解密(uniapp也可用)
https://blog.csdn.net/qq_40146789/article/details/118929205
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)