rsaJwkFromSpkiDer function

Map<String, Object?> rsaJwkFromSpkiDer(
  1. Uint8List spki, {
  2. String? keyId,
  3. String? algorithm,
  4. String? use,
})

Reads an RSA SubjectPublicKeyInfo DER back into a public JWK.

The inverse of rsaPublicKeyDerFromJwk, for publishing a key at a jwks_uri. Only kty, n and e come from the key itself; keyId, algorithm and use are metadata the caller chooses.

Implementation

Map<String, Object?> rsaJwkFromSpkiDer(
  Uint8List spki, {
  String? keyId,
  String? algorithm,
  String? use,
}) {
  final outer = DerReader(spki).read();
  if (outer.tag != 0x30) {
    throw const FormatException('Not a SubjectPublicKeyInfo: expected SEQUENCE');
  }

  final parts = outer.elements;
  if (parts.length < 2 || parts[1].tag != 0x03) {
    throw const FormatException(
      'Not a SubjectPublicKeyInfo: expected an AlgorithmIdentifier '
      'followed by a BIT STRING',
    );
  }

  final algorithmOid = parts[0].elements.first.oid;
  if (algorithmOid != '1.2.840.113549.1.1.1') {
    throw FormatException(
      'Only RSA public keys convert to a JWK here, got OID $algorithmOid',
    );
  }

  // Drop the "unused bits" byte that opens every BIT STRING.
  final keyBytes = Uint8List.sublistView(parts[1].content, 1);
  final rsaKey = DerReader(keyBytes).read().elements;
  if (rsaKey.length < 2) {
    throw const FormatException('Malformed RSAPublicKey: expected n and e');
  }

  Uint8List magnitude(DerValue integer) {
    final content = integer.content;
    // Strip the sign byte DER added; a JWK integer is unsigned.
    return content.length > 1 && content[0] == 0
        ? Uint8List.sublistView(content, 1)
        : content;
  }

  return <String, Object?>{
    'kty': 'RSA',
    'n': encodeBase64Url(magnitude(rsaKey[0])),
    'e': encodeBase64Url(magnitude(rsaKey[1])),
    if (keyId != null) 'kid': keyId,
    if (algorithm != null) 'alg': algorithm,
    if (use != null) 'use': use,
  };
}