node加密集合(前端加密、后台解密)

2023-12-14 09:31:33



一、crypto 加解密

  • cryptonode 的内置模块无需另外安装

生成私密钥

import { generateKeyPairSync, publicEncrypt, privateDecrypt } from 'crypto'

const { publicKey, privateKey } = generateKeyPairSync('rsa', {
    modulusLength: 1024,
    publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem'
    }
});

在这里插入图片描述

  • 把生成的公私秘钥保存(注意-------部分也是需要的,否则报错
// 公钥
export const PUBLIC_KEY = `
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC/NknF2LMwt77tg63x1KVXEz4Q
rKAGVhd9kUDxQaz6meP/Qy4OUDdDBGKanLkZ5n8e1YadxwHbR9XIUPohIvLNP3fm
tMGXO2oyq+TGQKmoAAuik4qtn7T3hwMAuKVClO3epgVmFMb9xbCufUE7N+xiKHa8
8z202y08jyQTVSdWHQIDAQAB
-----END PUBLIC KEY-----
`

// 私钥
export const PRIVATE_KEY = `
-----BEGIN PRIVATE KEY-----
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAL82ScXYszC3vu2D
rfHUpVcTPhCsoAZWF32RQPFBrPqZ4/9DLg5QN0MEYpqcuRnmfx7Vhp3HAdtH1chQ
+iEi8s0/d+a0wZc7ajKr5MZAqagAC6KTiq2ftPeHAwC4pUKU7d6mBWYUxv3FsK59
QTs37GIodrzzPbTbLTyPJBNVJ1YdAgMBAAECgYEAnB2y9foLs4cSN9H/PycjJ4jq
b6rBrOq1myvxHglFNgZXhJ5RCBauR+VYrGuxJVhwCbjEhCVreqGYBkk3L77dBRRS
FwBqeZanUtTBKtZ06KKwAgRzPt/BOMNn+GDqt36U/2AyUXWg1qLe5r9hLWCEau5r
Yt8vYFrBKIaxu8YKIIECQQDxmpPEbyg9uors3yJ2qf0jv6cemMOsH3An4TdIiINx
7kFD/01otwOGFVUexPJgeCsi5zsnVK0AzdrqY6z4XBiVAkEAypsJGE/cDJb66qe3
PAA+8nRqgi6VGfQ3weCHlQhTO/ho5xPZIu63MVKyMZIPJ1MXQmMVRoz2lLmApZBL
wz79aQJBAONVUalJ9pFuz33mz2TcuoZCtZuCnst8oWnE7uHfId+4Ec1LkqjvW+90
by2On4nKSLyE2xI9CLRy/oQB2iWvcqkCQQCxAIcOlV4yJYjqjkF3iuNzYB9YwieC
uCgqGeV5Xv+QifHjxyRQ72peDdgdlHPmsCHG3tdMfoRB5FouyoRV++bZAkAso9+8
rTBM9sMow4Dw/lbeQGbvqz+w2ayfWbA4s7q8eSb25gnaAGZGAJ2Yx608DoGjIOZa
e2IyCqybjWEy7ycZ
-----END PRIVATE KEY-----
`

公钥加密(也可私钥加密)

publicKey为上述生成的公钥

import { publicEncrypt } from 'crypto'

//需要加密的数据
const data = "data to crypto"
// 公钥加密过程
const encryptData = publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
console.log('encode:', encryptData);

私钥解密(也可公钥解密)

PRIVATE_KEY为上述生成的秘钥
encryptData为上述加密的值

import { privateDecrypt } from 'crypto'

// 私钥解密
const decryptData = privateDecrypt(PRIVATE_KEY, Buffer.from(encryptData, 'base64'));
console.log('decode:', decryptData.toString());

二、node-rsa加解密

生成公私秘钥

import NodeRSA from 'node-rsa'
let key = new NodeRSA({ b: 1024 })
    key.setOptions({ encryptionScheme:'pkcs1'})
    
let pubkey = key.exportKey('public') //生成公钥,发给前端用于数据加密
let privkey = key.exportKey('private')//生成私钥,用于数据解密
console.log(pubkey)
console.log(privkey)

在这里插入图片描述

使用公钥加密(也可私钥加密)

需要把密码先转为base64格式,并加上'base64', 'utf8'两个传参,避免出现乱码情况

let encrypt = new NodeRSA(pubkey)
// encrypt.setOptions({ encryptionScheme: 'pkcs1' })
const pass_word = encrypt.encrypt(Buffer.from("123456"), 'base64', 'utf8')
console.log(pass_word)

使用私钥解密(也可公钥解密)

let decrypt= new NodeRSA(privkey)
// decrypt.setOptions({ encryptionScheme: 'pkcs1' })
const s = pass_word.replace(/\s+/g, '+')
const decryptPass = decrypt.decrypt(s, 'utf8')
console.log('decode:', decryptPass)

在这里插入图片描述

三、前端项目使用jsencrypt加密

在前端项目使用前面两种加密会出现报错,发现并不支持前端项目
得使用jsencrypt加密

import JSEncrypt from "jsencrypt";
const encrypt = new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
console.log(encrypt.encrypt("123456"));

注意,后台解密的时候,需要确认秘钥生成格式
解密的时候需要设置对应格式,否则会出现解密失败的情况

decrypt.setOptions({ encryptionScheme: 'pkcs1' })

秘钥文件格式存放

文件

  • /src/const/secret-key/public.pem (存放公钥数据)
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwLgQqalNF4ge6PuDxmvcJtnFm
djh4YgkmKeTwve1L5gJglp/e/uRXRsBQxw0Vv0tAAIQA0sN036j5JTxGmcuxnuZ6
5Zw75jeaBQfE6+kgMD88cUnRlje3X3lMT2kRZsja+IowEvrLiUWuhV9rBPkskhxj
vJQd1A2+KaQU09lYYwIDAQAB
-----END PUBLIC KEY-----
  • /src/const/secret-key/private.pem (存放私钥数据)
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCwLgQqalNF4ge6PuDxmvcJtnFmdjh4YgkmKeTwve1L5gJglp/e
/uRXRsBQxw0Vv0tAAIQA0sN036j5JTxGmcuxnuZ65Zw75jeaBQfE6+kgMD88cUnR
lje3X3lMT2kRZsja+IowEvrLiUWuhV9rBPkskhxjvJQd1A2+KaQU09lYYwIDAQAB
AoGAaUemT55oErumeIJ4s4gyFcjDbUI6Lp4O75JbcA1fD1rsksGP2Zch5pGt/Ndm
F1fP5Pgp6cAI8v9wnynEIkBnesS0j+Ydu43b6f94CXW5BwvQjy3mmkMKDvE8MHcT
h/lEosAIFfbpHD+5Uhxu47ynQRXzP9OE5Rn//MjeAS94XtkCQQD6qOQ9r2r4SsOr
5Rqh0Fr6xZrPvV5tuO2fhe+WO1XeVXPe7Dizdlck/AyWn8fL2dUERn+KvBiUblOy
zuFbQv09AkEAs+7oaDT4pkkV1mLvb+VSIut2guzcGh5o7n3dkXEKnca9dACRMK5N
Vecp3dnbAtJJwpXMuP5eJJYEc74HH1ZGHwJAAZdQ25NhenH/C/hIUv6flTfr46Ww
E8I4v+p5utplkSO5uJCHS5xUsUdoTQx2mDSpxX0tEhRfk5GftmLZy1qBgQJAUJ/+
t6L0v94D0Pqn+2WwNkF36xajUXjK4AK6I4+ZiDUjczVF2aBguttIIUabIlqD/pMN
Ft+z44TtHcfKfTo1VQJAYcgb8uGXgZVz9fFZqAaE8I0W2JkGn4zsta+RjSwxTJj9
SHDuAXBVEeLpS4hM8CA4fHmti6A0ezqh9B3U750/DA==
-----END RSA PRIVATE KEY-----

引入

const fs = require('fs')
const path = require('path')
//读取私钥加密
const rsaS = fs.readFileSync(path.join(__dirname,'./const/secret-key/private.pem'));
console.log('rsaS_rsaS', rsaS.toString())

在这里插入图片描述


总结

如有启发,可点赞收藏哟~

文章来源:https://blog.csdn.net/weiCong_Ling/article/details/134976122
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。