问题
I am using CryptoJS to encrypt my epub (or zip)
file and decrypt it. I am using react native
to create the app. But I don't know why the decrypted file is not the original epub file. The error while opening the decrypted epub file is: Error in opening zip file.
And I am using react-native-fetch-blob
for file reading and writing.
Here is my code:
Encryption
encrypt() {
// ENCRYPTION
RNFetchBlob.fs.readFile(`${RNFetchBlob.fs.dirs.DownloadDir}/startup.epub`, 'base64')
.then(result => {
console.log('startup.epub read data: ', result);
// Encrypt
const ciphertext = AES.encrypt(result, key);
// Write encrypted file
RNFetchBlob.fs.writeFile(RNFetchBlob.fs.dirs.DownloadDir + '/startup_enc.dat', ciphertext.toString(), 'base64')
.then(() => {
console.log('startup_enc.dat file wrtten');
this.decrypt();
})
.catch(error => {
console.log('startup_enc.dat file writing error', error);
});
})
.catch(err => {
console.log('read error: ', err);
});
}
I read the epub file in
base64
format. I encrypted the result with AES asciphertext
Then I wrote theciphertext.toString()
tostartup_enc.dat
file inbase64
encoding.
Decryption
decrypt() {
// DECRYPTION
RNFetchBlob.fs.readFile(`${RNFetchBlob.fs.dirs.DownloadDir}/startup_enc.dat`, 'base64')
.then(result => {
console.log('startup_enc.dat data: ', result);
// Decrypt
const bytes = AES.decrypt(result, key);
const plaintext = bytes.toString(enc.Base64);
// Write decrypted file
RNFetchBlob.fs.writeFile(RNFetchBlob.fs.dirs.DownloadDir + '/startup_dec.epub', plaintext, 'base64')
.then(() => {
console.log('startup_dec.epub file wrtten');
})
.catch(error => {
console.log('startup_dec.epub file writing error', error);
});
})
.catch(err => {
console.log('read error: ', err);
});
}
Then I read the encrypted
startup_enc.dat
file inbase64
encoding. I decrypted the file and converted tobase64
format. Then I wrote the decryptedplaintext
tostartup_dec.epub
again inbase64
encoding format.
The size of original epub file is 2.49 MB
, encrypted file is 3.11 MB
and the decrypted epub file is also 3.11 MB
unlike 2.49 MB
.
I am unable to find where the problem is, either in encryption
or in decryption
process. Can anybody help?
- React-native-fetch-blob file streaming DOCS
- CryptoJS AES Encryption DOCS
来源:https://stackoverflow.com/questions/48238373/cryptojs-aes-decryption-not-giving-original-zip-epub-file-in-react-native