2011-05-12 50 views
2

我正在嘗試使用零填充的URL查詢字符串執行AES CBC加密。我正在使用NodeJS的核心加密模塊。這是用於與http://www.blackoutrugby.com/game/help.documentation.php#category=35這個簡單的NodeJS加密函數有什麼問題?

我有一個關鍵和四。當測試下面的函數時,我沒有收到完整的字符串。我相信這與填充有關,但我不確定如何正確應用它。

如果是填充,任何人都可以告訴我應該如何應用它?如果不是我哪裏錯了?這個用例中的cipher.final()也有意義嗎?

更新: 我現在已經包括cipher.final()和事情工作正常與二進制格式但base64給了我截斷的結果。 https://github.com/denishoctor/BlackoutRugbyNode/blob/master/crypto2.js是我完整的示例代碼。下面是加密功能:

function cryptoTest(data, key, iv, format) { 
    var cipher = crypto.createCipheriv('aes-128-cbc', key, iv); 
    var cipherChunks = []; 
    cipherChunks.push(cipher.update(data, 'utf8', format)); 
    cipherChunks.push(cipher.final()); 

    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv); 
    var plainChunks = []; 
    for (var i = 0;i < cipherChunks.length;i++) { 
     plainChunks.push(decipher.update(cipherChunks[i], format, 'utf8')); 
    } 
    plainChunks.push(decipher.final()); 

    return { 
     "encrypted": cipherChunks.join(''), 
     "decrypted": plainChunks.join('') 
    }; 
} 

感謝,
丹尼斯

回答

5

你是不是把由cipher.final返回到破譯密文。這是一個簡單的例子。您需要從每次調用cipher.update以及cipher.final時收集返回值,並確保每個對象都被解密.update。

UPDATE:這裏有一個正常工作與binaryhex作爲編碼爲密文版本,但失敗base64。我不知道這是爲什麼,但如果你很好,用十六進制應該可以正常工作。

UPDATE 2:看起來像base64是節點本身的錯誤。見this answer to a similar question

var crypto = require('crypto'); 

    var data = "I am the clear text data"; 
    console.log('Original cleartext: ' + data); 
    var algorithm = 'aes-128-cbc'; 
    var key = 'mysecretkey'; 
    var clearEncoding = 'utf8'; 
    var cipherEncoding = 'hex'; 
    //If the next line is uncommented, the final cleartext is wrong. 
    //cipherEncoding = 'base64'; 
    var cipher = crypto.createCipher(algorithm, key); 
    var cipherChunks = []; 
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding)); 
    cipherChunks.push(cipher.final(cipherEncoding)); 
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join('')); 
    var decipher = crypto.createDecipher(algorithm, key); 
    var plainChunks = []; 
    for (var i = 0;i < cipherChunks.length;i++) { 
     plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding)); 

    } 
    plainChunks.push(decipher.final(clearEncoding)); 
    console.log("UTF8 plaintext deciphered: " + plainChunks.join('')); 
+0

謝謝你。這是一個很大的幫助。但是,當我添加base64編碼時,我得到一個截斷的結果!並且想法爲什麼? > – 2011-05-24 04:02:51

+0

您的原始源代碼混合了output_encoding base64和binary。這是我的猜測。讓我以一致的base64來嘗試我的例子。 – 2011-05-24 04:18:31

+0

我現在已經更新了這個問題,並有一個完整的示例@ https://github.com/denishoctor/BlackoutRugbyNode/blob/master/crypto2.js – 2011-05-24 04:35:38