Files
ClassContent/项目合集/电商App/shop_backend/utils/rsa.js
2025-02-19 00:34:51 +08:00

63 lines
1.7 KiB
JavaScript

const NodeRsa = require("node-rsa");
const fs = require("fs");
const path = require("path");
const config = require("../config");
class Rsa {
constructor() {
this.private_key = this.readFiles(this.getFilePath(config.rsa.private_key))
this.public_key = this.readFiles(this.getFilePath(config.rsa.public_key))
this.pri_rsa = new NodeRsa(this.private_key,'pkcs8-private-pem')
this.pri_rsa.setOptions({ encryptionScheme: 'pkcs1' })
this.pri_rsa.setOptions({ environment: "browser" });
this.pub_rsa = new NodeRsa(this.public_key,'pkcs8-public-pem')
this.pub_rsa.setOptions({ encryptionScheme: 'pkcs1' })
this.pub_rsa.setOptions({ environment: "browser" });
}
// // 公钥加密
// PublicKeyEncryption(text) {
// return (new NodeRsa(this.public_key)).encrypt(JSON.stringify(text), 'base64')
// }
// // 公钥解密
// PublicKeyDecryption(text) {
// return JSON.parse((new NodeRsa(this.public_key)).decryptPublic(text, 'utf8'))
// }
// // 私钥加密
// PrivateKeyEncryption(text) {
// return (new NodeRsa(this.private_key)).encryptPrivate(JSON.stringify(text), 'base64')
// }
// 私钥解密
PrivateKeyDecryption(text) {
return JSON.parse(this.pri_rsa.decrypt(text, 'utf8'))
}
/**
* 获取path.join文件地址
* @param paths
* @returns {string}
*/
getFilePath(paths) {
return path.join(__dirname, paths)
}
/**
* 读取文件数据
* @param path
* @returns {*}
*/
readFiles(path) {
return fs.readFileSync(path).toString()
}
}
module.exports = new Rsa();