【问题标题】:Decrypting AES256 encrypted data in .NET from node.js - how to obtain IV and Key from passphrase从 node.js 解密 .NET 中的 AES256 加密数据 - 如何从密码中获取 IV 和密钥
【发布时间】:2012-09-05 16:42:27
【问题描述】:

我有以下代码来加密/解密 node.js 中的数据,它正在工作:

var cipher = crypto.createCipher('aes256', 'passphrase');  
var encrypted = cipher.update("test", 'utf8', 'base64') + cipher.final('base64');

var decipher = crypto.createDecipher('aes256', 'passphrase');   
var plain = decipher.update(encrypted, 'base64', 'utf8') + decipher.final('utf8');

我希望能够在 C#/.NET 中做同样的事情,这样我就可以在两个独立的系统之间共享数据。但是,我在 .NET 中看到的代码需要密钥和 IV 才能进入/解密。这些是如何从 node.js Crypto 库中的密码短语派生而来的?

【问题讨论】:

    标签: c# .net node.js encryption


    【解决方案1】:

    node.js source 我发现了这个:

     bool CipherInit(char* cipherType, char* key_buf, int key_buf_len) {
    cipher = EVP_get_cipherbyname(cipherType);
    if(!cipher) {
      fprintf(stderr, "node-crypto : Unknown cipher %s\n", cipherType);
      return false;
    }
    
    unsigned char key[EVP_MAX_KEY_LENGTH],iv[EVP_MAX_IV_LENGTH];
    int key_len = EVP_BytesToKey(cipher, EVP_md5(), NULL,
      (unsigned char*) key_buf, key_buf_len, 1, key, iv);
    

    我在this question 中找到了 EVP_BytesToKey 的 c# 实现,可以这样使用:

    byte[] key, iv;
    DeriveKeyAndIV(Encoding.ASCII.GetBytes("passphrase"),null, 1, out key, out iv);
    
                         //this is what node.js gave me as the base64 encrypted data
    var encrytedBytes = Convert.FromBase64String("b3rbg+mniw7p9aiPUyGthg==");
    

    然后可以在 RijndaelManaged 的实例中使用密钥和 IV 来解密 encrytedBytes

    【讨论】:

    • 如果我使用带有 unicode 的密码,对字节的编码与 node.js 使用的不同......有什么提示吗?
    • Nodejs 使用Latin1 encoding。您需要使用Encoding.GetEncoding("ISO-8859-1") 而不是 ASCII
    猜你喜欢
    • 2016-06-09
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多