最近在使用strapi5开发接口API文档,徐需要做一个非对称加密,记录下一种简单的生成方式
生成 RSA 私钥、公钥对
执行命令
openssl genrsa -out private.pem 1024
查看私钥 cat private.pem
执行命令,根据私钥生成公钥
openssl rsa -in private.pem -pubout -out public.pem
加密代码
const crypto = require('crypto')
const {publicKey, privateKey} = require('./config');
const rsaEncrypt = (str) => {
return crypto.publicEncrypt(publicKey, str).toString('hex');
}
const rsaDecrypt = (str) => {
return crypto.privateDecrypt(privateKey, Buffer.from(str, 'hex')).toString();
}
module.exports = {
rsaDecrypt,
rsaEncrypt
}
挂在全局
在strapi的入口文件
'use strict';
const utils = require('./helpers/utils') // 扩展工具
// const services = require("./server/services");
// console.log(services)
module.exports = {
/**
* An asynchronous register function that runs before
* your application is initialized.
*
* This gives you an opportunity to extend code.
*/
register({strapi}) {
strapi.$utils = utils
},
/**
* An asynchronous bootstrap function that runs before
* your application gets started.
*
* This gives you an opportunity to set up your data model,
* run jobs, or perform some special logic.
*/
bootstrap(/*{ strapi }*/) {
},
};