符合Good Node JS AES标准的Encrypt Decrypt模块

时间:2014-08-14 13:54:34

标签: node.js

我正在寻找一个Node JS模块来加密和解密字符串,如下面的PHP代码:

function encrypt($decrypted) {
    // salt
    $salt = '!mysalthere123456789';
    // Build a 256-bit $key which is a SHA256 hash of $salt and $password.
    $key = hash('SHA256', $salt ."supersecretkey13456789", true);
    // Build $iv and $iv_base64. We use a block size of 128 bits (AES compliant) and CBC mode. (Note: ECB mode is inadequate as IV is not used.)
    srand();
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
    if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22)
        return false;
        // Encrypt $decrypted and an MD5 of $decrypted using $key. MD5 is fine to use here because it's just to verify successful decryption.
    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
    // We're done!
    return $iv_base64 . $encrypted;
}

基本上,这会返回一个随机加密的字符串,即使您保留相同的IV和密码(与许多其他始终返回相同加密字符串的加密工具不同)

我不是计算机专家,因此不知道如何将其转换为Node Js所以我正在寻找一个现有模块来帮助我完成我的小项目。

有谁知道一个好的?我已经测试了十几个,但它们总是返回相同的值。

2 个答案:

答案 0 :(得分:0)

var crypto = require('crypto');
var bcrypt = require('bcrypt-nodejs');

var SALT = bcrypt.genSaltSync(10);

function encrypt(text, key){
   var cipher = crypto.createCipher('aes-256-cbc',SALT + key)
   var crypted = cipher.update(text,'utf8','hex')
   crypted += cipher.final('hex');
   return crypted;
}

function decrypt(text, key){
   var decipher = crypto.createDecipher('aes-256-cbc',SALT + key)
   var dec = decipher.update(text,'hex','utf8')
   dec += decipher.final('utf8');
   return dec;
}

答案 1 :(得分:0)

kruptein可以轻松处理所有AES密钥大小和模式。除非您明确告知,否则它也不会重复使用ivaad(其他身份验证数据)。

const kruptein = require('kruptein');

kruptein.init({secret: 'squirrel'});

let ciphertext = kruptein.set('Some kind of secret');
let plaintext = kruptein.get(ciphertext);