I made an encryption tool for encoding texts and txt files. The tool gets 8 bit binary code of input char then encrypts it with other functions for ex:
a.txt file has:
xxyz
reader = fs.createReadStream('./a.txt', {
flag: 'r',
encoding: 'UTF-8',
highWaterMark: 1
})
reader.on('data', function (chunk) {
console.log( chunk + " --> " + toBin(chunk) )
//writer.write( toStr(reverse(toBin(chunk))) );
});
////////////// TRANSLATORS //////////////
function toBin(text)
return (
Array
.from(text)
.reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
.map(bin => '0'.repeat(8 - bin.length) + bin )
.join('')
);
}
function toStr(bin) {
return String.fromCharCode(parseInt(bin, 2))
}
OUTPUT:
x --> 01111000
x --> 01111000
y --> 01111001
z --> 01111010
--> 00001010
The last one is EOL, I think. To encrypt this I basically use my functions like:
function swap(bin) {
return bin.slice(4, 8) + bin.slice(0, 4)
}
function reverse(bin) {
return bin.split("").reverse().join("")
}
Then these functions works well for txt files. I can decrypt and encrypt.
When I try the same way on a png file for ex, there is a problem:
console.log( chunk + " --> " + toStr(toBin(chunk)) )
writer.write( toStr(toBin(chunk)) );
/* OUT
® --> ®
B --> B
` --> `
-->
*/
That looks nice when we look the output, but when we try to open the file it created and not empty it says:
"Couldn't load image, unrecognized image file format.
When I try to open image with text editor:
Original png image Just used string to binary, binary to string, wrote to new file.
As you can see, they are not same. I think I shouldn't read it like reading a text file. So how should I read it?
NOTE: Tried more tobin functions but that's the most true one because some of them were saying range error because of reading a big file than txt files, some of them were giving 7 bit codes, and some of them was giving 000 or undefined sometimes.
Thanks.
I think it is about how you write the image file. I hope this helps.
You need write it as: buffer or binary
// in this states data must be as binary
fs.writeFile("file.png", data, "binary", cb)
// other case you can write with streams
fs.createWriteStream("file.png", {
encoding: "binary"
})
writer.write(chunks);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.