我的问题是我写了一个加密和解密文件但不能正确解密的程序。我使用AES-256算法。
文件系统: 项目文件夹中有文件:
main.js
package.json
package-lock.json
files
text1.txt
这是main.js文件:
// Import modules
fs = require('fs');
aes = require('aes256');
// Change directory
process.chdir('files');
// Choosing global variables
path = process.cwd();
key = 'test';
// Encrypt and decrypt files
enc = file => {
return aes.encrypt(key,file)
}
decr = encr => {
return aes.decrypt(key,encr)
}
// Encrypt file
fl = fs.readFileSync('file1.txt').toString();
fs.writeFileSync('file1.txt',enc(fl));
// Timeout
setTimeout(()=> {
// Read file again and decrypt
newfl = fs.readFileSync('file1.txt').toString()
fs.writeFileSync('file1.txt',decr(fl))
}, 3000);
如果我运行node main
,它将首先加密文件,然后解密:
第一步:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
第二步:
wuv5VqCy3BEC1TeCikiZeYVNHTCJh5eDLCMgTIaKbMk95rBO6419DSUxjCC2d6Ps4s6UtiNSimFFLjzeDWlUML8W3KXNCGrEzu1aj5w9+uUHj34PSBTOLm6ynWs/SPVKoSl5oc5Fn4lGf4CxhuTLUD0C3UnuYwmQ/RYcYtCB/s1t2HiHUxluU4GUs9ge7j8mJUjj55fklaFJ+D9S1nBGIIQj47itbpY+5znnFv4bBumNeurV31F1Igf60ZSNScXFs5dg6oROhZiY33/DxvuwcewqElQzdXbfinHa7h99vl0hSvqSmHOH3Txt/vMQuGc8UovHZFwNsRN6uME0iQ+U+O71aXN6+gf1sn81fDdUB3t7vlgzjn6fEAQdrXSlUq75IFAYbOPnndyzkLFcGI6fklCMFq0JwwbhdtTlCijmah3hTKf1Lm6oQrOOLHkJG3nIxLengVauH9gWUYbJWdZEH7ygqnQbC/LC278bEsQXEwkCte+3Y6paBrgER/LwWFxgYnol0nVS2+kv1wa7zbf+aJhuLXidLVxX49cv1Uq+h0sbcXTSizTuOv9OzUfG8Ykmg9DMBo7Fu1RWBRh85AHZEYVFW8li/79dEgTRzjT5CHg=</pre>
第三步:
e|´��x���>�!4��5������$�ʊ��
f�sٹYa��A��+.-mҧ5p
为什么不解密回来?
答案 0 :(得分:1)
您需要将加密的文件内容传递给decr功能,您要传递旧的文件内容进行解密
更改
setTimeout(()=> {
// Read file again and decrypt
newfl = fs.readFileSync('file1.txt').toString()
fs.writeFileSync('file1.txt',decr(fl))
}, 3000);
到
setTimeout(()=> {
// Read file again and decrypt
newfl = fs.readFileSync('file1.txt').toString()
fs.writeFileSync('file1.txt',decr(newfl))
}, 3000);