I have an app that writes data to a file line by line. Once finished, the data needs to be zipped and transmitted to a server. I want to make sure that after zipping but before transmitting the data to the server, the data is secure. Thus, I want to encrypt the zip (or the contents). Moreover, I want to use asymmetric encryption because the source code will be viewed by others.

Is there any way to do this in flutter/dart?

My alternative solution would be to read the data back into the app, encrypt it, write it again, and then zip it. What are your thoughts?

Solution 1: Stefano Amorelli

As @Topaco accurately stated, asymmetric encryption of a large file comes with important performance drawbacks.

It can be achieved by splitting the file into smaller chunks of data and encrypting each part. But again, this is not recommended.

That said, you encrypt/decrypt a String with RSA using the rsa_encrypt package for Flutter:

import 'package:rsa_encrypt/rsa_encrypt.dart';
import 'package:pointycastle/api.dart' as crypto;

//Future to hold our KeyPair
Future<crypto.AsymmetricKeyPair> futureKeyPair;

//to store the KeyPair once we get data from our future
crypto.AsymmetricKeyPair keyPair;

Future<crypto.AsymmetricKeyPair<crypto.PublicKey, crypto.PrivateKey>> getKeyPair()
var helper = RsaKeyHelper();
return helper.computeRSAKeyPair(helper.getSecureRandom());

- Generate KeyPair with the function getKeyPair() store the returned value in futureKeyPair.

- Once we get data from the future we can store that data in keyPair (Now we have acces to our private and public key).

- In order to view our keys as "a string" we need to use two functions encodePrivateKeyToPemPKCS1(keyPair.privateKey) & encodePublicKeyToPemPKCS1(keyPair.publicKey).

- In order to encrypt and decrypt strings you can use two functions

- encrypt() : use this function to encrypt a string, pass your string as first argument and a public key as the second one. [IMPORTANT]: this will return a string so you should store the returned value in a variable.

- decrypt() : use this function to decrypt an encrypted String, pass your encrypted String as first argument and a private key as the second. this will also return a string dont forget to store it :)

A solution to encrypt a file would be to use a safe symmetric encryption algorithm with a random secret key, which is then encrypted with an asymmetric algorithm. This approach is commonly referred to as hybrid cryptosystem.