美文网首页
thinkjs ---- nodejs rsa 加密解密

thinkjs ---- nodejs rsa 加密解密

作者: 无我_a50f | 来源:发表于2020-06-13 11:38 被阅读0次

    web 客户端

    import JSEncrypt from 'jsencrypt/bin/jsencrypt.min';
    const encrypted = new JSEncrypt();
    encrypted.setPublicKey(`-----BEGIN PUBLIC KEY-----${window.ENV.publicKey}-----END PUBLIC KEY-----`);
    encrypted.encrypt('加密的数据');
    

    nodejs 服务端

    const NodeRSA = require('node-rsa');
    const decrypt = new NodeRSA('-----BEGIN RSA PRIVATE KEY-----私钥串-----END RSA PRIVATE KEY-----');
    // 查看 https://github.com/rzcoder/node-rsa/issues/91
    decrypt.setOptions({encryptionScheme: 'pkcs1'});
    decrypt.decrypt('解密的字符串');
    

    附录:
    thinkjs 中间件中获取post 数据 middleware/payload.js

    const _ = require('lodash');
    const NodeRSA = require('node-rsa');
    const decrypt = new NodeRSA(think.config('custom.privateKey'));
    // 查看 https://github.com/rzcoder/node-rsa/issues/91
    decrypt.setOptions({encryptionScheme: 'pkcs1'});
    
    module.exports = (options, app) => {
        return async(ctx, next) => {
            if(ctx.header['content-type'] == 'application/json'){
                let postData = await new Promise((resolve, reject) => {
                    try {
                        let str = "";
                        ctx.req.on("data", chunk => {
                            str += chunk;
                        });
                        ctx.req.on("end", data => {
                            console.log(str);
                            resolve(str);
                        });
                    } catch (e) {
                        reject(e);
                    }
                });
    
                _.forEach(JSON.parse(postData), (item, key) => {
                    ctx.post(key, decrypt.decrypt(item, 'utf-8'));
                });
            }
    
            return next();
        }
    }
    

    相关文章

      网友评论

          本文标题:thinkjs ---- nodejs rsa 加密解密

          本文链接:https://www.haomeiwen.com/subject/cpyatktx.html