如何在nodejs中加密和解密字符串/对象

Mar*_*inh 5 encryption node.js cryptojs node-crypto

我想加密一个对象然后解密它。加密效果很好,但解密失败。下面是我的代码:

加密扩展.js

const crypto = require("crypto")
const password = "shared_key"
const algorithm = "aes256"

export const encrypt = (text) => {
    if(!text) return ''
    const cipher = crypto.createCipher(algorithm, password);
    let crypted = cipher.update(text, 'utf-8', 'base64');
    crypted += cipher.final('base64');
    return crypted;
}

export const decrypt = (text) => {
    if(!text) return ''
    const decipher = crypto.createDecipher(algorithm, password);
    let decrypted = decipher.update(text, 'base64', 'utf-8');
    decrypted += decipher.final('utf-8');
    return decrypted;
}
Run Code Online (Sandbox Code Playgroud)

在我的test.js中,我有:

import {encrypt, decrypt} from './crypto_ext.js'
let test = {key1: val1, key2: val2}
test = encrypt(JSON.stringify(test)) || test
console.log("Encrypt : ", test)
console.log("Decrypt : ", decrypt(test)) // I should have my object as string here
Run Code Online (Sandbox Code Playgroud)

这就是我得到的错误:

Uncaught Error: unable to decrypt data
at unpad (decrypter.js:83)
at Decipher.webpackJsonp../node_modules/browserify-aes/decrypter.js.Decipher._final (decrypter.js:38)
at Decipher.webpackJsonp../node_modules/cipher-base/index.js.CipherBase._finalOrDigest (index.js:76)
at decrypt (crypto_ext.js:17)
...
Run Code Online (Sandbox Code Playgroud)

你能告诉我我做错了什么吗?

Shr*_*oel -1

尝试使用“bcrypt”包,它将帮助您加密密码。如果你想对数据进行加密。然后使用 crypto 或 node-rsa

链接npm bcrypt 包

节点RSA

  • bcrypt 是密码哈希/KDF,与加密/解密无关。 (4认同)