nginx - 如何使用njs解密aes256加密的字符串?

标签 nginx njs

sha 256 加密代码(来自文档)

function hmacEncrypt(r) {
    let str = r.uri.split("/", 2)
    return require('crypto').createHash('sha256', 'key')
                          .update(str)
                          .digest('base64url');
}

我想使用njs来解码aes256、base64编码的字符串。 不过njs官方文档只展示了加密方法。 有没有办法解码或编码 aes256?我可以帮你吗?

最佳答案

对于 aes256,您可以执行以下操作:

const crypto = require("crypto");

const initVector = new Uint8Array([
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
]);

function encryptString(string, securityKey) {
    const cipher = crypto.createCipheriv(
        'aes-256-cbc',
        securityKey,
        initVector
    );
    cipher.update(string, 'utf-8', 'hex');
    return cipher.final('hex');
}

function decryptString(string, securityKey) {
    const decipher = crypto.createDecipheriv(
        'aes-256-cbc',
        securityKey,
        initVector
    );
    decipher.update(string, 'hex', 'utf-8');
    return decipher.final('utf-8');
}

initVector 是提供算法的初始状态,您可以将其更改为任何您想要的,但它应该是一个正好 16 字节的数组,然后只需使用这些函数即可:

const securityKey = new Uint8Array([
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
    31, 32
]);

const text = 'example string';
const encrypted = encryptString(text, securityKey);
const decrypted = decryptString(encrypted, securityKey);

console.log(encrypted);
console.log(decrypted);

securityKey key 是用于加密和解密字符串的密码,它应该是一个正好 32 字节的数组,将其更改为您想要的任何内容!

关于nginx - 如何使用njs解密aes256加密的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68629307/

相关文章:

ubuntu - stream_get_contents():SSL 操作失败,代码为 1。OpenSSL 错误消息:错误:0A000126:SSL 例程::读取时出现意外 eof

ruby-on-rails - 服务器重启后如何重启 RoR 服务

linux - 如何在 nginx.conf 中将 GitLab 配置为子域

nginx - 在 docker-compose 的命令键中使用容器的环境变量

node.js - 通过nodejs、njs脚本语言扩展nginx

javascript - 有没有办法在javascript中访问nginx.var

ruby-on-rails-3 - Rails Nginx 乘客无法结帐 session ,因为发生了生成错误