4

I would like to encrypt an object then decrypt it. The encryption works very well but the decryption fails. Below my code :

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

and in my test.js, I have :

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

And this is what I'm getting as error :

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

Can you please tell me what I'm doing wrong ?

Maria Minh
  • 1,219
  • 4
  • 15
  • 27

3 Answers3

1
  1. Method createCipher deprecated. Use createCipheriv instead.
  2. Try to use aes192 algorithm.
Volodymyr Sichka
  • 531
  • 4
  • 10
1

Dependencies: crypto package

You can achieve encoding and decoding with below codes:-

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

And then call below functions for encode and decode

For encode

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

For decode

await decode('encoded_string_to_decode');
waseem asgar
  • 664
  • 8
  • 20
-2

Try to use 'bcrypt' package it will help you in the encryption for passwords. If you want to encryption for Data. Then use crypto or node-rsa

Link npm bcrypt package

Node-RSA

Shraddha Goel
  • 869
  • 7
  • 18
  • 4
    bcrypt is a password hash/KDF and has nothing to do with encryption/decryption. – Luke Joshua Park Jul 24 '18 at 08:33
  • Hey Shraddha. Thanks for your feedback but this module is more useful for passwords encryption. What I want to do is to encrypt my string firstly and pass it as parameter in the URL and depending on this param I can decrypt it and show its content in other pages. – Maria Minh Jul 24 '18 at 08:34
  • Hi, Now I understand what you actually looking for here. I read your Description in short and hence lead to the wrong answer. You can try ' https://www.npmjs.com/package/node-rsa' this package Node RSA I used to encrypt and decrypt my data. – Shraddha Goel Jul 24 '18 at 08:47
  • 1
    @MariaMinh can you tell me which package you are using because crypto is deprecated now. Crypto.js is a new one – Shraddha Goel Jul 24 '18 at 08:54
  • @ShraddhaGoel I used Crypto.js but I'm facing an other error in decryption. I got "Error: Malformed UTF-8 data"... – Maria Minh Jul 24 '18 at 10:48
  • I used "cryptr" instead, it works very well :) Thanks for your assistance @ShraddhaGoel – Maria Minh Jul 24 '18 at 11:01
  • @MariaMinh Thanks – Shraddha Goel Jul 24 '18 at 12:16