2014-01-21 32 views
1

使用Node.js的加密庫,我加密的PDF像這樣:解密了內容加密的PDF後,解密的結果是空

//encrypting the pdf 
fs.readFile('./full.pdf', function (err,data) { 
    if (err) { 
     return console.log(err); 
    } 
    var cipher = crypto.createCipher('aes-256-cbc', encPassword); 
    var text = data; 
    var crypted = cipher.update(text,'utf8','hex'); 
    crypted += cipher.final('hex'); 
    console.log(crypted); 
}); 

然後我去crypted並運行它通過:

var decipher = crypto.createDecipher('aes-256-cbc', encPassword); 
var dec = decipher.update(args[0],'hex','utf8'); 
dec += decipher.final('utf8');            

fs.writeFileSync('./output.pdf', dec); 

./output.pdf現在是一個空白頁面,它應該是充滿原始內容。

當我使用完全相同的代碼(不含fs.writeFileSync('./output.pdf', dec);)來加密和解密一個簡單的字符串進行加密和解密完美。

+0

在'decipher.update'調用之前''args [0]'中有什麼? – vbo

+0

由於加密和解密是2個獨立的腳本。爲了解密,我把第一個('$ crypted')的輸出作爲解密腳本的命令行參數使用 – bzupnick

+0

如果你試圖在一個腳本中加入編碼和解碼步驟,並通過js變量傳遞它,該怎麼辦? – vbo

回答

0

問題出在寫作上。解密dec輸出一個字符串。該字符串必須轉換爲二進制緩衝區,並將其寫入文件。

作品像現在一個魅力:

var decipher = crypto.createDecipher('aes-256-cbc', encPassword); 
var dec = decipher.update(args[0],'hex','binary');        
dec += decipher.final('binary');  

var buffer = new Buffer(dec, "binary");           
fs.writeFileSync('./output.pdf', buffer); 
+0

所以我是對的;)對我來說,它的工作原理是這樣的:'fs.writeFileSync('./ output.pdf',dec,'binary')'。 – vbo

+0

你非常有幫助,但問題不是二元問題。這是我沒有寫緩衝區。 – bzupnick

0

您可以使用node-qpdf包進行加密和解密的PDF文件。它使用qpdf