2013-12-09 47 views
1

爲什麼不打印「你好」?節點加密 - 無法反向加密

var cipher = crypto.createCipheriv('rc4', 'secret', ''); 
crypt = cipher.update('hello', 'binary', 'utf8'); 
crypt += cipher.final('utf8'); 

var decipher = crypto.createDecipheriv('rc4','secret', ''); 
data = decipher.update(crypt, 'binary', 'utf8'); 
data += decipher.final('utf8'); 

console.log(data); // prints e/l 

回答

4

utf8是不是一個有效的cipher.final()選項,你想要二進制。嘗試這個。

var cipher = crypto.createCipheriv('rc4', 'secret', ''); 
crypt = cipher.update('hello', 'utf8', 'binary'); 
crypt += cipher.final('binary'); 

var decipher = crypto.createDecipheriv('rc4','secret', ''); 
data = decipher.update(crypt, 'binary', 'utf8'); 
data += decipher.final('utf8'); 

console.log(data); 
+0

不。拋出「AssertionError:無法更改編碼」錯誤 – cyberwombat

+0

對不起,沒有更改cipher.update。編輯我的答案,試試看。 – AronVietti

1

沃金碼:

var crypto = require('crypto'); 
var ecr = function(str) 
{ 
    var cipher = crypto.createCipher('aes-256-cbc', 'passphase'); 
    var cryptedBuffers = [cipher.update(new Buffer(str))]; 
    cryptedBuffers.push(cipher.final()); 
    var crypted = Buffer.concat(cryptedBuffers); 
    return crypted; 
}; 
var dcr = function(str) 
{ 
    var dcipher = crypto.createDecipher('aes-256-cbc', 'passphase'); 

    var dcryptedBuffers = [dcipher.update(new Buffer(str))]; 
    dcryptedBuffers.push(dcipher.final()); 
    var dcrypted = Buffer.concat(dcryptedBuffers) 
     .toString('utf8'); 
    return dcrypted; 
}; 

console.log(dcr(ecr('hello test')));