wcEncrypt function

String wcEncrypt({
  1. required String message,
  2. required String symKeyHex,
  3. int type = 0,
  4. required Uint8List iv,
  5. String? senderPublicKeyHex,
})

Encrypt message into a base64 WC envelope.

type 0: base64( 0x00 || iv(12) || ciphertext || tag ) type 1: base64( 0x01 || senderPublicKey(32) || iv(12) || ciphertext || tag )

Implementation

String wcEncrypt({
  required String message,
  required String symKeyHex,
  int type = 0,
  required Uint8List iv,
  String? senderPublicKeyHex,
}) {
  if (iv.length != _ivLength) {
    throw ArgumentError('iv must be $_ivLength bytes');
  }
  if (type == 1 && senderPublicKeyHex == null) {
    throw ArgumentError('type 1 envelope requires senderPublicKey');
  }
  final ct = chacha20Poly1305Encrypt(
    key32: hexDecode(symKeyHex),
    nonce12: iv,
    plaintext: Uint8List.fromList(utf8.encode(message)),
  );

  final out = <int>[type];
  if (type == 1) {
    final pub = hexDecode(senderPublicKeyHex!);
    if (pub.length != _keyLength) {
      throw ArgumentError('senderPublicKey must be $_keyLength bytes');
    }
    out.addAll(pub);
  }
  out.addAll(iv);
  out.addAll(ct);
  return base64.encode(out);
}