2012-09-04 99 views
1

獲得IV和密鑰i有以下代碼的加密/解密的node.js數據,這是工作:解密AES256從node.js的在.NET加密數據 - 如何從密碼短語

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中看到的代碼需要Key和IV才能進入/解密。它們是如何從node.js Crypto庫中的密碼派生的?

回答

2

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=="); 

密鑰和IV然後可以在使用RijndaelManaged的一個實例解密encrytedBytes

+0

如果我使用帶unicode的密碼短語,字節的編碼不同於node.js u ses ...任何提示? – Tracker1

+0

Nodejs使用[Latin1 encoding](https://nodejs.org/api/crypto.html#crypto_crypto_createcipher_algorithm_password)。您需要使用'Encoding.GetEncoding(「ISO-8859-1」)'而不是ASCII –