2013-04-04 42 views
1

爲什麼下面的代碼拋出了一個DecipherFinal錯誤密碼 -錯誤密碼破譯

var crypto = require('crypto'); 
    c=new Date; 
    x= (c.getTime()+"."+c.getMilliseconds()).toString()+".uIn"; 
    key = 'sevsolut' 
     , plaintext = x 
     , cipher = crypto.createCipher('aes-256-cbc', key) 
     , decipher = crypto.createDecipher('aes-256-cbc', key); 
    cipher.update(plaintext, 'utf8', 'base64'); 
    var encryptedPassword = cipher.final('base64') 

    decipher.update(encryptedPassword, 'base64', 'utf8'); 
    var decryptedPassword = decipher.final('utf8'); 

    console.log('encrypted :', encryptedPassword); 
    console.log('decrypted :', decryptedPassword); 
+0

'C =新Date'應'c = new Date()' – pfried 2013-04-04 08:23:30

+0

你爲什麼要加密密碼而不是散列它們? – Mchl 2013-04-04 08:38:18

+0

只要你不需要傳遞參數,在JS中實例化對象時@pfried括號是可選的。 – robertklep 2013-04-04 08:53:59

回答

2

你需要從更新的輸出:

var crypto = require('crypto'); 
c=new Date(); 
x= (c.getTime()+"."+c.getMilliseconds()).toString()+".uIn"; 
key = "sevsolut" 
     , plaintext = x 
     , cipher = crypto.createCipher('aes-256-cbc', key) 
     , decipher = crypto.createDecipher('aes-256-cbc', key); 
var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64'); 
encryptedPassword += cipher.final('base64') 

var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8'); 
decryptedPassword += decipher.final('utf8'); 

console.log('encrypted :', encryptedPassword); 
console.log('decrypted :', decryptedPassword); 
+0

@ chris..it工作完美:) ..however想要指出一件事..有問題的代碼似乎完美地適用於特定長度的字符串(嘗試使用一個簡單的小字符串)..只有當它超過一定的長度時,我猜我們必須添加更新步驟。你可以點亮它嗎? – digster 2013-04-04 10:38:00

+0

不確定你的意思。更新返回加密的內容,並且在流式傳輸時可以使用新數據多次調用 - 最終返回所有剩餘的加密內容。 – laktak 2013-04-04 11:03:36

+0

我的意思是說使用x =「簡單」作爲明文輸入..然後問題中的代碼完美地工作..但是如果x =一些大字符串..然後問題中的代碼失敗,我們必須根據您的例子.... – digster 2013-04-04 12:42:18