encryptMessage method

Future<EncryptedPayload> encryptMessage(
  1. String key,
  2. String plainText
)

Implementation

Future<EncryptedPayload> encryptMessage(String key, String plainText) async {

  // Initialize algorithm
  final algorithm = cryptography.Chacha20.poly1305Aead();

  // Encode Key
  cryptography.SecretKey secretKey = cryptography.SecretKey(utf8.encode(key));
  // Encode encrypted text
  List<int> clearText = utf8.encode(plainText);
  // Encrypt
  final nonce = algorithm.newNonce();
  final cryptography.SecretBox secretBox = await algorithm.encrypt(
    clearText,
    secretKey: secretKey,
    nonce: nonce,
  );

  String base64Data = base64Encode(secretBox.cipherText);
  String base64Mac = base64Encode(secretBox.mac.bytes);

  return EncryptedPayload(
    base64Data: base64Data,
    dataLength: secretBox.cipherText.length,
    base64Mac: base64Mac,
    base64Nonce: base64Encode(secretBox.nonce),
  );
}