encrypt method
Encrypt: returns nonce(12) | ciphertext | tag(16).
Implementation
Uint8List encrypt(Uint8List key, Uint8List plaintext) {
final nonce =
Uint8List.fromList(List.generate(12, (_) => _rng.nextInt(256)));
return using((a) {
final hAlg = _openGcmAlg(a);
final hKey = _genSymKey(a, hAlg, key);
try {
final nonceP = a<Uint8>(12)..asTypedList(12).setAll(0, nonce);
final tagP = a<Uint8>(16);
final inP = a<Uint8>(plaintext.isEmpty ? 1 : plaintext.length);
if (plaintext.isNotEmpty) {
inP.asTypedList(plaintext.length).setAll(0, plaintext);
}
final outP = a<Uint8>(plaintext.isEmpty ? 1 : plaintext.length);
final info = _authInfo(a, nonceP, tagP);
final cbResult = a<Uint32>();
final st = _encryptFn(hKey, inP, plaintext.length, info.cast(), nullptr,
0, outP, plaintext.length, cbResult, 0);
if (st != _statusSuccess) {
throw StateError('BCryptEncrypt failed (status=$st)');
}
final ctLen = cbResult.value;
final out = Uint8List(12 + ctLen + 16);
out.setRange(0, 12, nonce);
if (ctLen > 0) out.setRange(12, 12 + ctLen, outP.asTypedList(ctLen));
out.setRange(12 + ctLen, out.length, tagP.asTypedList(16));
return out;
} finally {
_destroyKey(hKey);
_closeAlg(hAlg, 0);
}
});
}