uniapp applet implements RSA encryption

introduction

When developing front-end, encryption is sometimes inevitably used. I used asymmetric encryption such as RSA in this small program project, so I recorded the use this time.

Create and use jsencrypt for RSA encryption

When you download jsencrypt or reference the package from npm in the uniapp applet, an error will be reported due to different elements between the applet and h5, so you need to change the jsencrypt file. You can click the link below to download and use the jsencrypt file.

Download link: https://download.csdn.net/download/m0_64344940/86812930

Create rsa file

// rsa.js
import Jsencrypt from '@/utils/jsencrypt.js'; // 此处是上面的文件引用

let publicKey =
	'-----BEGIN PUBLIC KEY-----' +  // 必须添加,切记
	'' +  // 此处使用后端给的公钥
	'-----END PUBLIC KEY-----'   // 必须添加,切记
	
// msg 类型为 string 字符串,不能搞错类型,不然生成之后的内容后端会解密失败
export const rsaEncrypt = (msg) => {
    
    
	const JsRsa = new Jsencrypt()
	JsRsa.setPublicKey(publicKey)
	return JsRsa.encrypt(msg)
}

Quote where needed

This project is used in the request header of the interface

import {
    
     rsaEncrypt } from '@/utils/rsa.js'

export const request = (option) => {
    
    
	// 事先定义好,可以防止时间差导致解密出来的时间戳和传值的时间戳不一样
	const times = new Date().getTime()
	
    ...
	
	header["sign"] = rsaEncrypt(times.toString())
	header["timestamp"] = times
}

Notice

The parameters of the rsaEncrypt method must be strings, not other types! ! !

Welcome all the experts to give you advice. If there are any mistakes, please point them out. Thank you.

Guess you like

Origin blog.csdn.net/m0_64344940/article/details/127489366