rsaPrivateKeyDerFromJwk function
Builds a PKCS#1 RSAPrivateKey DER from the private half of an RSA jwk.
The CRT parameters (dp, dq, qi) are optional in a JWK — some
generators omit them — but PKCS#1 requires all nine integers, so they are
derived from d, p and q when absent.
Implementation
Uint8List rsaPrivateKeyDerFromJwk(Map<String, Object?> jwk) {
_requireRsa(jwk);
final n = _requireField(jwk, 'n');
final e = _requireField(jwk, 'e');
final d = _requireField(jwk, 'd');
final p = _requireField(jwk, 'p');
final q = _requireField(jwk, 'q');
final dBig = _toBigInt(d);
final pBig = _toBigInt(p);
final qBig = _toBigInt(q);
if (pBig <= BigInt.one || qBig <= BigInt.one) {
throw const FormatException('JWK has invalid RSA primes');
}
Uint8List optional(String name, BigInt Function() derive) {
final present = jwk[name];
return present is String && present.isNotEmpty
? decodeBase64Url(present)
: _fromBigInt(derive());
}
return _derSequence([
_derInteger(Uint8List.fromList(const [0])), // version: two-prime
_derInteger(n),
_derInteger(e),
_derInteger(d),
_derInteger(p),
_derInteger(q),
_derInteger(optional('dp', () => dBig % (pBig - BigInt.one))),
_derInteger(optional('dq', () => dBig % (qBig - BigInt.one))),
_derInteger(optional('qi', () => qBig.modInverse(pBig))),
]);
}