54 lines
1.3 KiB
JavaScript
54 lines
1.3 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))
|
|
}
|
|
|
|
|
|
// 公钥加密
|
|
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((new NodeRsa(this.private_key)).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();
|