CryptoJS AES Decryption Not Giving original ZIP/EPUB file in react native

无人久伴 提交于 2019-12-13 18:43:33

问题


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 as ciphertext Then I wrote the ciphertext.toString() to startup_enc.dat file in base64 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 in base64 encoding. I decrypted the file and converted to base64 format. Then I wrote the decrypted plaintext to startup_dec.epub again in base64 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?

  1. React-native-fetch-blob file streaming DOCS
  2. CryptoJS AES Encryption DOCS

来源:https://stackoverflow.com/questions/48238373/cryptojs-aes-decryption-not-giving-original-zip-epub-file-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!