Home > Software design >  How to fetch pdf file from internet, then encrypt it and store it and then decrypt and load in futur
How to fetch pdf file from internet, then encrypt it and store it and then decrypt and load in futur

Time:11-12

I'm working on a project that fetches pdf file from the internet then have to encrypt and store it on the device. Then for future use, it has to decrypt the encrypted pdf file and load it.

This is the method to fetch the pdf file :

  Future<String> fetchThenStorePdf(DownloadedBook book) async {
    var pdfPath = await getBookUrl(book);
    book.bookFilePath = Uri.http('http://www.marakigebeya.com.et/mabdocuments/audio_e_books/fa872915-f364-4129-b373-06c1df078c00..pdf', pdfPath).toString();
    final response = await client
        .get(Uri.parse('${book.bookFilePath}'))
        .timeout(Duration(minutes: 3), onTimeout: () {
      throw Exception('connection timed out');
    });
    if (response.statusCode == 200) {
      print('The pdf file is ${response.bodyBytes}');
      return await storeEncryptedPdf(
        response.body,
        bookTitle: book.title,
      );
    } else {
      throw Exception('PDF file not found');
    }
  }

This method will call storeEncryptedPdf() method which looks like :

Future<String> storeEncryptedPdf(String pdfByteFile,
      {required String bookTitle}) async {
    await PermissionHandler.requestStoragePermission();
    try {
      var directory = await getApplicationDocumentsDirectory();
      var bookDirectory = await Directory(path.join(
        '${directory.path}',
        'books',
      )).create(recursive: true);
      final filePath = path.join(bookDirectory.path, '$bookTitle');
      final file = File(filePath);
      var encryptedData = encryptionHandler.encryptData(pdfByteFile);
      await file.writeAsString(encryptedData, flush: true);
      return filePath;
    } catch (e) {
      throw Exception('File encryption failed');
    }
  }

which inturn will call the encryptData() method:

 String encryptData(String fileToEncrypt) {
    key = Key.fromUtf8(encryptionKeyString);
    iv = IV.fromUtf8(encryptionKeyString);
    final encrypter = Encrypter(
      AES(
        key,
        padding: null,
      ),
    );
    Encrypted encrypted = encrypter.encrypt(
      fileToEncrypt,
      iv: iv,
    );
    return encrypted.base64;
  }

I used the encrypt: ^5.0.1 flutter package for the encryption and deccription.

The decryption method is :

  Future<String> decryptStoredPdf(String filePath) async {
    encryptionHandler.encryptionKeyString = 'theencryptionkey';
    final file = File(filePath);
    final byteFile = await file.readAsString();
    return encryptionHandler.decryptData(byteFile);
  }

where filepath is the path of the file stored. This method finally calls the method decryptData :

String decryptData(String filetoDecrypt) {
    key = Key.fromUtf8(encryptionKeyString);
    iv = IV.fromUtf8(encryptionKeyString);
    final encrypter = Encrypter(
      AES(
        key,
        padding: null,
      ),
    );
    String decrypted = encrypter.decrypt(
      Encrypted.from64(filetoDecrypt),
      iv: iv,
    );
    return decrypted;
  } 

But all this is not working. Can someone pls replicate this and try to figure out what the problem is

CodePudding user response:

You have to manipulate with bytes, but not with strings. Just read bytes, encrypt/decrypt bytes, create/read file from bytes.

  • Related