generateKey static method
Generate an RSASSA-PSS 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 RsaPssPrivateKey.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....
// Use the same saltLength for signing and verifying
const saltLength = 256 / 8;
// Sign a message for Alice.
final message = 'Hi Alice';
final signature = await keyPair.privateKey.signBytes(
utf8.encode(message),
saltLength,
);
// 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 RsaPssPublicKey.importSpkiKey(
PemCodec(PemLabel.publicKey).decode(pemPublicKey),
Hash.sha256,
);
final isValid = await publicKey.verifyBytes(
signature,
utf8.encode(message),
saltLength,
);
if (isValid) {
print('Authentic message from Bob: $message');
}
Implementation
static Future<KeyPair<RsaPssPrivateKey, RsaPssPublicKey>> generateKey(
int modulusLength,
BigInt publicExponent,
Hash hash,
) {
return impl.rsaPssPrivateKey_generateKey(
modulusLength,
publicExponent,
hash,
);
}