How to Perform File encryption with Flutter and Dart

做~自己de王妃 提交于 2020-06-16 02:54:29

问题


I don't know if it is right to ask my question here. I just need to make a feasibility study for an App I am trying to build. I chose Flutter because I allow to quickly create mobile apps.

My application will be storing voice messages in forms of audio files. It can be an mp3 or an audio format.

To make it readable by the receiver only, I need to encrypt the file using may be AES or e2e encryption.

I need to know if it is possible to encrypt files with Dart in my flutter app. If it is possible, I would like to get useful resources.

I tried to search for this topic, but I can only find articles about encrypting string or text files.


回答1:


Finally found something. I tried multiple options including the encrypt package, but all were dead ends. I finally found this package It can encrypt files using AES all you need is the path to the file. It is well documented. I believe its best to create a class and add functions for encrypt and decrypt as I have did below.

import 'dart:io';
import 'package:aes_crypt/aes_crypt.dart';

class EncryptData {
  static String encrypt_file(String path) {
    AesCrypt crypt = AesCrypt();
    crypt.setOverwriteMode(AesCryptOwMode.on);
    crypt.setPassword('my cool password');
    String encFilepath;
    try {
      encFilepath = crypt.encryptFileSync(path);
      print('The encryption has been completed successfully.');
      print('Encrypted file: $encFilepath');
    } catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The encryption has been completed unsuccessfully.');
        print(e.message);
      }
      else{
        return 'ERROR';
      }
    }
    return encFilepath;
  }

  static String decrypt_file(String path) {
    AesCrypt crypt = AesCrypt();
    crypt.setOverwriteMode(AesCryptOwMode.on);
    crypt.setPassword('my cool password');
    String decFilepath;
    try {
      decFilepath = crypt.decryptFileSync(path);
      print('The decryption has been completed successfully.');
      print('Decrypted file 1: $decFilepath');
      print('File content: ' + File(decFilepath).path);
    } catch (e) {
      if (e.type == AesCryptExceptionType.destFileExists) {
        print('The decryption has been completed unsuccessfully.');
        print(e.message);
      }
      else{
        return 'ERROR';
      }
    }
    return decFilepath;
  }
}


Now you can use it like

encrypted_file_path = EncryptData.encrypt_file('your/file/path');


来源:https://stackoverflow.com/questions/58324907/how-to-perform-file-encryption-with-flutter-and-dart

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