encryptBytes abstract method
Encrypt data
such that it can only be decrypted with
RsaOaepPrivateKey.decryptBytes from the matching private key.
The optional label
may be used to provide arbitrary data that will not
be encrypted, but instead specifies important context for the data
.
If an RsaOaepPublicKey is used to encrypt multiple kinds of data,
then using a unique label
for each kind of data ensures that
data encrypted for one purpose cannot be reused for another purpose by
an adversary.
For further discussion of labels, see
section 2.1.4 of "A Proposal for an ISO Standard for Public Key Encryption".
The size of the data
to be encrypted is limited to
data.length <= (modulusLength - 2 * hashLength - 2) / 8
, where
hashLength
and modulusLength
are given in bits.
For example, a 2048 bit RSA key with Hash.sha256 cannot encrypt messages
larger than 191 bytes.
For this reason, RSAES-OAEP is often used to encrypt/decrypt a random
one-time key for a symmetric cipher like AesCbcSecretKey,
AesCtrSecretKey or AesGcmSecretKey, after which the symmetric cipher
is used to encrypt/decrypt larger messages.
Example
import 'dart:convert' show utf8;
import 'package:webcrypto/webcrypto.dart';
import 'package:pem/pem.dart';
// Generate a key-pair.
final keyPair = await RsaOaepPrivateKey.generateKey(
4096,
BigInt.from(65537),
Hash.sha256,
);
// Alice sends keyPair.publicKey to Bob
// Bob can generate a 256 bit symmetric secret key
final secretKeyToBeShared = await AesGcmSecretKey.generateKey(256);
// Using the public key Bob can encrypt secretKeyToBeShared, such that it
// can only be decrypted with the private key.
final encryptedRawKey = await keyPair.publicKey.encryptBytes(
await secretKeyToBeShared.exportRawKey(),
label: 'shared-key-exchange',
);
// Bob sends Alice: encryptedRawKey
// Given privateKey and encryptedRawKey Alice can decrypt the shared key.
final sharedRawSecretKey = await keypair.privateKey.decryptBytes(
encryptedRawKey,
label: 'shared-key-exchange',
);
final sharedSecretKey = await AesGcmSecretKey.importRaw(
sharedRawSecretKey,
);
// Now both Alice and Bob share a secret key.
Implementation
// Note: A decent explanation of the [label] is available in:
// Section 2.1.4 of "A Proposal for an ISO Standard for Public Key Encryption"
// Version 2.1, by Victor Shoup, 2001.
// https://www.shoup.net/papers/iso-2_1.pdf
//
// See also documentation for crypto/rsa in golang:
// https://pkg.go.dev/crypto/rsa#EncryptOAEP
Future<Uint8List> encryptBytes(List<int> data, {List<int>? label});