WishMeLz

生活其实很有趣

非对称加密(node-rsa,jsencrypt)

公钥私钥生成

随便找个在线生成的

http://www.metools.info/code/c80.html

OR

const NodeRSA = require('node-rsa')
const fs = require('fs')

const newkey = new NodeRSA({ b: 512 })
newkey.setOptions({ encryptionScheme: 'pkcs1' })

let public_key = newkey.exportKey('pkcs8-public') //公钥
let private_key = newkey.exportKey('pkcs8-private') //私钥


fs.writeFileSync('./pub.pem', public_key)
fs.writeFileSync('./pri.pem', private_key)

前端加密

import NodeRSA from 'node-rsa';

    const PUBLIC_KEY = '你的PUBLIC_KEY';
    let clientKey = new NodeRSA(`-----BEGIN PUBLIC KEY-----${PUBLIC_KEY}-----END PUBLIC KEY-----`);
    //指定RSA加密协议,pkcs1 或 pkcs1_oaep,默认pkcs1_oaep
    clientKey.setOptions({encryptionScheme: 'pkcs1'}); 
    const result = clientKey.encrypt('这个是铭文', 'base64'); // 指定输出编码类型为base64
    console.log(result);
<script src="https://cdn.bootcss.com/jsencrypt/3.0.0-beta.1/jsencrypt.min.js"></script>
<script>
    let publicKey = `-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAMyBBK6yUEom72wb/VEgmMEBl41M6KVm
n32XH+Kbz45TKBEoFF6kP53vWF/Y7QS3i1g/vM6Y21hk2k1natGZm3MCAwEAAQ==
-----END PUBLIC KEY-----
`

    var encrypt = new JSEncrypt()
    encrypt.setPublicKey(publicKey)
    var encrypted = encrypt.encrypt('这个是铭文2')

    console.log(encrypted);
</script>

uniapp版的

https://github.com/WishMelz/file/blob/master/js/jsencrypt.js

import JSEncrypt from '@/utils/jsencrypt.js'
 let publicKey = `publicKey`
    let pubKey = `-----BEGIN PUBLIC KEY-----${publicKey}-----END PUBLIC KEY-----`;
    var encrypt = new JSEncrypt()
    encrypt.setPublicKey(pubKey)
    var encrypted = encrypt.encrypt('2这个是铭文2')
    console.log(encrypted);

NodeJs 解密

const fs = require('fs')
const NodeRSA = require('node-rsa')

let text = 'hHMVSagzqNb0feA763dLacT1WAtbsdnoXDogijwDJN5HpNODrQ/oHaWJb1GRu7xk/h2S3yT7x2MxI38GYfCbuQ=='
let private_key = fs.readFileSync('./private.pem', 'utf8')
const prikey = new NodeRSA(private_key)
prikey.setOptions({ encryptionScheme: 'pkcs1' })

console.log(prikey.decrypt(text, 'utf8'));
const fs = require('fs')
const NodeRSA = require('node-rsa')
let text = 'y9X7Bgppp16wGdTTQC/9P8C1zixjigpW3LVj5zhiR+wKSx05aA1ZHszHjohscVRXaEDLIbzmtaIvIkA646eX+Q=='
function justRsa(has) {
    let private_key = fs.readFileSync('./private.pem', 'utf8')
    const prikey = new NodeRSA(private_key)
    prikey.setOptions({ encryptionScheme: 'pkcs1' })
    let resText = ''
    try {
        resText = prikey.decrypt(has, 'utf8')
    } catch (error) {
        resText = '解析失败!!!'
    }
    return resText
}