encrypt method

String encrypt(
  1. dynamic value
)

If an Aes object is already set, this will use that object. Otherwise, it will...

  1. Create a new Aes object.
  2. Create a new AES key and set it on the object.
  3. Create a new IV and set it on the object.

Either way, next this will RSA encrypt the AES key, encrypt the value using the Aes object.

The returned string will be encoded as: ${rsaEncryptedAesKey}:${base64Iv}:${base64EncryptedValue}

Implementation

String encrypt(dynamic value) {
  List<int> bytes;

  if (value == null) {
    throw Exception('Required value is null');
  } else if (value is List<int>) {
    bytes = value;
  } else if (value is Uint8List) {
    bytes = value.toList();
  } else if (value is String) {
    bytes = utf8.encode(value);
  } else {
    bytes = utf8.encode(value.toString());
  }

  final publicKey = _publicKey;
  if (publicKey == null) {
    throw Exception('RSA attempted to encrypt but [publicKey] is null');
  }

  final aes = _aes ?? Aes();
  final key =
      aes._key ?? SecureRandom(256 /* bits */ ~/ 8 /* bits-per-byte */).bytes;

  final result = aes.key(key).encrypt(bytes);
  final encryptedKey = RSA(
    encoding: _encoding,
    publicKey: _publicKey,
  ).encrypt(key);

  return '${encryptedKey.base64}:$result';
}