The front-end js uses jsrsasign to generate an RSA key and obtain a series of information (public key, private key, modulus, exponent, etc.) for encryption and decryption

Preface:
When RSA encryption and decryption used in previous projects, a fixed public key (modulus, exponent) and private key are generated and placed in the code to decrypt the data. Now it is necessary to modify the front-end to generate (modulus and exponent) and pass it to the background. Background encrypted data is returned to me. I am decrypting with private key.
After a lot of research, the method in window.crypto at the beginning can generate public and private keys, but this can only be used in browsers, and cannot be used in applets. So give up.
Then there is this jsrsasign method that is more comprehensive. So choose to use this one.

Simple knowledge introduction of rsa
It is recommended to read this article Mr.
Ruan said RSA article. Simply speaking, in the process of generating the secret key, several numbers q, p, n, d, e are generated; q
, p are two unequal prime numbers n are randomly selected . Let's go straight to using






use
download

npm install jsrsasign -s

introduce

	import jsrsasign from 'jsrsasign'

Get public and private keys

	var rsaKeypair = jsrsasign.KEYUTIL.generateKeypair('RSA',1024);
	let PUBLIC = jsrsasign.KEYUTIL.getPEM(rsaKeypair.prvKeyObj);  //获取公钥
	let PRIVATE = jsrsasign.KEYUTIL.getPEM(rsaKeypair.prvKeyObj,'PKCS8PRV');  //获取私钥

Get the base64 data of the modulus

	let Modulus = jsrsasign.hextob64nl(rsaKeypair.prvKeyObj.n.toString(16));  //进行模数转换base64   获得base64数据
	//这里的模数是直接转base64数据传给后台的,如果需要hex的就得在次编码

get index

let info = jsrsasign.KEYUTIL.getJWK(rsaKeypair.prvKeyObj);
let Exponent = info.e;   //获取指数

The above is obtained according to the format of my needs.
If your needs are different from this, just perform data conversion.
As long as you know that n is the modulus and e is the exponent
jsrsasign There are many other methods and formats that you can check
the jsrsasign document by yourself

encryption

	var prv = jsrsasign.KEYUTIL.getKey(PUBLIC );   //传入公钥
	var iis  = prv.encrypt('11111111');  //加密

decrypt

	var prv = jsrsasign.KEYUTIL.getKey(PRIVATE);  //传入私钥
	var keyStr = prv.decrypt(jsrsasign.b64tohex(keyStrTemporary));   //我这边的需求是返回的base64  所以我又转成16进制。 本身就是16进制,不需要在去转

Guess you like

Origin blog.csdn.net/weixin_44655037/article/details/126746637