generateKey static method

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

Generate an RSASSA-PKCS1-v1_5 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 RsassaPkcs1V15PrivateKey.generateKey(
  4096,
  BigInt.from(65537),
  Hash.sha256,
);

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

// Sign a message for Alice.
final message = 'Hi Alice';
final signature = await keyPair.privateKey.signBytes(
  utf8.encode(message),
);

// On the other side of the world, Alice has written down the pemPublicKey
// on a trusted piece of paper, but receives the message and signature
// from an untrusted source (thus, desires to verify the signature).
final publicKey = await RsassaPkcs1V15PublicKey.importSpkiKey(
  PemCodec(PemLabel.publicKey).decode(pemPublicKey),
  Hash.sha256,
);
final isValid = await publicKey.verifyBytes(
  signature,
  utf8.encode(message),
);
if (isValid) {
  print('Authentic message from Bob: $message');
}

Implementation

static Future<KeyPair<RsassaPkcs1V15PrivateKey, RsassaPkcs1V15PublicKey>>
    generateKey(
  int modulusLength,
  BigInt publicExponent,
  Hash hash,
) {
  return impl.rsassaPkcs1V15PrivateKey_generateKey(
    modulusLength,
    publicExponent,
    hash,
  );
}