generateKey static method

Future<KeyPair<RsaOaepPrivateKey, RsaOaepPublicKey>> generateKey(
  1. int modulusLength,
  2. BigInt publicExponent,
  3. Hash hash
)

Generate an RSAES-OAEP public/private key-pair.

The modulusLength, given in bits, determines the size of the RSA key. A larger key size (higher modulusLength) is often consider more secure, but generally associated with decreased performance. This can be particularly noticible during key-generation on limited devices CPUs.

Using a modulusLength less than 2048 is often discouraged (see NIST SP 800-57 Part 1 Rev 5, section 5.6). Common key size include 2048, 3072 and 4096 for guidance on key-size see NIST SP 800-57 Part 1 Rev 5 or keylength.com for a comparison of various recommendations.

The publicExponent must be given as BigInt. Currently, this package has opted to only support 3 and 65537 as publicExponent, these are also the only values supported by Chrome. To generate RSA keys with a different publicExponent use a different package for key generation. It is common to use 65537 as publicExponent, see Wikipedia on RSA for an explanation of publicExponent (and RSA in general).

The hash algorithm to be used is specified by hash. Be ware that use of Hash.sha1 is discouraged.

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,
);

// Export public, so Bob can use it
final spkiPublicKey = await keyPair.publicKey.exportSpkiKey();
final pemPublicKey = PemCodec(PemLabel.publicKey).encode(spkiPublicKey);
print(pemPublicKey); // print key in PEM format: -----BEGIN PUBLIC KEY....
// Alice sends pemPublicKey to Bob

// Bob can generate a 256 bit symmetric secret key
final secretKeyToBeShared = await AesGcmSecretKey.generateKey(256);

// Using publicKey Bob can encrypt secretKeyToBeShared, such that it can
// only be decrypted with the private key.
final publicKey = RsaOaepPublicKey.importSpki(
  PemCodec(PemLabel.publicKey).decode(pemPublicKey),
  Hash.sha256,
)
final encryptedRawKey = await publicKey.encryptBytes(
  await secretKeyToBeShared.exportRawKey(),
  label: 'shared-key',
);
// Bob sends Alice: encryptedRawKey

// Given privateKey and encryptedRawKey Alice can decrypt the shared key.
final sharedRawSecretKey = await keypair.privateKey.decryptBytes(
  encryptedRawKey,
  label: 'shared-key',
);
final sharedSecretKey = await AesGcmSecretKey.importRaw(
  sharedRawSecretKey,
);
// Now both Alice and Bob share a secret key.

Implementation

static Future<KeyPair<RsaOaepPrivateKey, RsaOaepPublicKey>> generateKey(
  int modulusLength,
  BigInt publicExponent,
  Hash hash,
) {
  return impl.rsaOaepPrivateKey_generateKey(
    modulusLength,
    publicExponent,
    hash,
  );
}