如何在Node.js中加密和解密字符串/对象

时间:2018-07-24 08:12:01

标签: node.js encryption cryptojs node-crypto

我想先加密然后解密。加密效果很好,但是解密失败。在我的代码下面:

crypto_ext.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;
}

在我的 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

这就是我得到的错误:

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)
...

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

4 个答案:

答案 0 :(得分:0)

  1. 方法createCipher已过时。请改用createCipheriv
  2. 尝试使用aes192算法。

答案 1 :(得分:0)

为什么要重新发明轮子?有很多模块可以提供帮助。 kruptein可以轻松处理所有AES密钥大小和模式。

 Sub AddText
 Dim r as range
 Set r = range("a2") 'set pointer
 Do 'begin loop 
    r.formula = "Result " & r.row + 1 & ": " & r.text  'adjust contects
    set r = r.offset(1,0) 'move pointer
 Loop until r ="" 'keep going until blank cell
 End Sub

答案 2 :(得分:0)

依赖项: crypto

您可以使用以下代码实现编码和解码:-

   const crypto = require('crypto');
        var password = 'ojisdasjdsjabdjs';
        var iv = 'kiamdksndn';

        function sha1(input) {
            return crypto.createHash('sha1').update(input).digest();
        }

        function password_derive_bytes(password, salt, iterations, len) {
            var key = Buffer.from(password + salt);
            for (var i = 0; i < iterations; i++) {
                key = sha1(key);
            }
            if (key.length < len) {
                var hx = password_derive_bytes(password, salt, iterations - 1, 20);
                for (var counter = 1; key.length < len; ++counter) {
                    key = Buffer.concat([key, sha1(Buffer.concat([Buffer.from(counter.toString()), hx]))]);
                }
            }
            return Buffer.alloc(len, key);
        }


        async function encode(string) {
            var key = password_derive_bytes(password, '', 100, 32);
            var cipher = crypto.createCipheriv('aes-256-cbc', key, Buffer.from(iv));
            var part1 = cipher.update(string, 'utf8');
            var part2 = cipher.final();
            const encrypted = Buffer.concat([part1, part2]).toString('base64');
            return encrypted;
        }

        async function decode(string) {
            var key = password_derive_bytes(password, '', 100, 32);
            var decipher = crypto.createDecipheriv('aes-256-cbc', key, Buffer.from(iv));
            var decrypted = decipher.update(string, 'base64', 'utf8');
            decrypted += decipher.final();
            return decrypted;
        }

然后调用以下函数进行编码和解码

用于编码

await encode(JSON.stringify({'title': 'some text'}));

用于解码

await decode('encoded_string_to_decode');

答案 3 :(得分:-2)

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

链接npm bcrypt package

Node-RSA