使用node.js解密使用c#加密的数据

时间:2013-04-29 03:21:54

标签: c# node.js encryption cryptography rijndael

我现在面临一个需要你帮助的问题。

我使用c#进行一些加密。然后需要使用node.js来解密它。但我发现我无法根据我的c#加密算法正确地做到这一点。如果你们有任何解决方案,请帮助我。

这是我的c#加密代码:

public static string Encrypt(string text, String password, string salt, string hashAlgorithm, int passwordIterations, string initialVector, int keySize)
{
    if (string.IsNullOrEmpty(text))
        return "";

    var initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
    var saltValueBytes = Encoding.ASCII.GetBytes(salt);
    var plainTextBytes = Encoding.UTF8.GetBytes(text);
    var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
    var keyBytes = derivedPassword.GetBytes(keySize / 8);
    var symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    byte[] cipherTextBytes = null;
    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
    {
        using (var memStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                cryptoStream.FlushFinalBlock();
                cipherTextBytes = memStream.ToArray();
                memStream.Close();
                cryptoStream.Close();
            }
        }
    }
    symmetricKey.Clear();
    return Convert.ToBase64String(cipherTextBytes);
}
public static string Decrypt(string text, String password, string salt, string hashAlgorithm, int passwordIterations, string initialVector, int keySize)
{
    if (string.IsNullOrEmpty(text))
        return "";

    var initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
    var saltValueBytes = Encoding.ASCII.GetBytes(salt);
    var cipherTextBytes = Convert.FromBase64String(text);
    var derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
    var keyBytes = derivedPassword.GetBytes(keySize / 8);
    var symmetricKey = new RijndaelManaged();
    symmetricKey.Mode = CipherMode.CBC;
    var plainTextBytes = new byte[cipherTextBytes.Length];
    var byteCount = 0;
    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
    {
        using (var memStream = new MemoryStream(cipherTextBytes))
        {
            using (var cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
            {

                byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
                memStream.Close();
                cryptoStream.Close();
            }
        }
    }
    symmetricKey.Clear();
    return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);    
}

如果有人可以为nodejs提供相同的功能,那将是非常有帮助的。无论如何,感谢阅读这篇文章。

2 个答案:

答案 0 :(得分:2)

首先,我们将使用Node.js执行PasswordDeriveBytes函数。这是crypto.pbkdf2

// assumes HMAC-SHA1
crypto.pbkdf2(password, salt, iterations, keySize / 8, function(err, key) {
    if(err) /* handle error */
    // ...
});

接下来,使用crypto.createDecipheriv创建解密器:

// find algorithm from the available ciphers; see crypto.getCiphers()
var decipher = crypto.createDecipheriv(/* algorithm */, key, initialVector);

然后使用decipher.updatedecipher.final向其提供数据。他们会将部分解密数据返回给您。

答案 1 :(得分:0)

在完全相同的情况下,我能够使用上面的@icktoofay提供的代码成功获得“C#encrypt =&gt; Node decrypt”解决方案,使用 PasswordDeriveBytes < / strong>替换为 Rfc2898DeriveBytes

我的代码大致是:

C#

private byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(salt);

public string Encrypt<T>(string value, string password) where T: SymmetricAlgorithm, new() {
  byte[] valueBytes = UTF8Encoding.UTF8.GetBytes(value);

  byte[] encrypted = null;
  using (T cipher = new T()) {
    var db = new Rfc2898DeriveBytes(password, saltBytes);
    db.IterationCount = iterationsConst;
    var key = db.GetBytes(keySizeConst / 8);

    cipher.Mode = CipherMode.CBC;

    using (ICryptoTransform encryptor = cipher.CreateEncryptor(key, vectorBytes)) {
      using (MemoryStream ms = new MemoryStream()) {
        using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) {
          cs.Write(valueBytes, 0, valueBytes.Length);
          cs.FlushFinalBlock();
          encrypted = ms.ToArray();
        }
      }
    }
    cipher.Clear();
  }
  return Convert.ToBase64String(encrypted);
}

JavaScript的:

var crypto = require('crypto');
var base64 = require('base64-js');
var algorithm = 'AES-256-CBC';

[...]

var saltBuffer = new Buffer(salt);
var passwordBuffer = new Buffer(password);

[...]

var encodedBuffer = new Buffer(base64.toByteArray(encryptedStringBase64Encoded));

crypto.pbkdf2(passwordBuffer, saltBuffer, iterations, keySize / 8, function(err, key) {
  var decipher = crypto.createDecipheriv(algorithm, key, iv);
  var dec = Buffer.concat([decipher.update(encodedBuffer), decipher.final()]);
  return dec;
});

实际上是我在互联网上找到的一些例子的组合。

因为在某些特定情况下我对Buffer的Base64实现有问题(在编码字符串的开头是'+'符号),我使用了来自https://github.com/beatgammit/base64-js的base64-js,这似乎工作正常。