encrypt<Text, Key> method
- Text? plainText,
- Key? key,
- {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}) {
assert(plainText != null && key != null);
areParamsVaild(plainText, key, options: options);
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 = 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 = _runAes(
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 = _runAes(
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,
);
}