encrypt<Text, Key> method

  1. @override
CipherParams encrypt<Text, Key>(
  1. Text? plainText,
  2. Key? key,
  3. {CipherOptions? options}
)
override

The encrypt method takes in plain text, a key, and optionally an initialization vector (iv) and cipher options. It returns a CipherParams object which contains the encrypted data. The method is generic and can work with any type of data for the plain text, key, and iv.

Implementation

@override
CipherParams encrypt<Text, Key>(Text? plainText, Key? key,
    {CipherOptions? options}) {
  areParamsVaild(plainText, key);
  final Uint8List encrypted;

  final Uint8List ctbytes = getPlaintText(plainText, enc.Utf8);

  final Uint8List _key;

  final Uint8List _iv;

  final mode = options?.mode ?? Mode.CBC;
  final paddingUsed = options?.padding ?? pad.Padding.PKCS7;
  final padding = getPadding(paddingUsed);
  final Uint8List? salt;
  if (key is String && options?.keyEncoding == null) {
    salt = getSalt(options?.salt ?? generateSalt(_SALT_SIZE), _SALT_SIZE);
    final keyAndIV = crypto.CryptoDart.EvpKDF(
      password: enc.Utf8.parse(key),
      keySize: _KEY_SIZE,
      ivSize: _IV_SIZE,
      salt: salt,
      hasher: _KDF_DIGEST,
      iterations: 1,
    );

    _key = keyAndIV.key;
    _iv = keyAndIV.iv;

    final cipherText = _runTripleDes(
        forEncryption: true,
        key: _key,
        iv: _iv,
        plaintext: ctbytes,
        mode: mode,
        padding: padding);

    var sbytes = enc.Utf8.parse(_APPEND);
    var b = Uint8List(_IV_SIZE + cipherText.length);

    arrayCopy(sbytes, 0, b, 0, sbytes.length);
    arrayCopy(salt, 0, b, _SALT_SIZE, _SALT_SIZE);
    arrayCopy(cipherText, 0, b, 16, cipherText.length);

    encrypted = b;
  } else {
    _key = getKey(key, options?.keyEncoding);

    _iv = getIV(options?.iv, _IV_SIZE, options?.ivEncoding);
    salt = null;
    encrypted = _runTripleDes(
        forEncryption: true,
        iv: _iv,
        key: _key,
        mode: mode,
        padding: padding,
        plaintext: ctbytes);
  }

  return CipherParams(
    cipherText: encrypted,
    iv: _iv,
    key: _key,
    mode: mode,
    padding: paddingUsed,
    salt: salt,
  );
}