Files
skills/docs/security-stack/crypto/crypto-rsa/src/keys/serialize-jwk.md
2026-05-29 08:20:56 +01:00

1.6 KiB

keys/serialize-jwk

Purpose

Inverse of parseRsaPublicKeyJwk and parseRsaPrivateKeyJwk. Emits an RsaJwk with every numeric field encoded as base64url per RFC 7515 §2 (URL-safe alphabet, no padding) over the minimum-length big-endian representation of each bigint per RFC 7518 §6.3.

Features

  • Per-field base64url encoding via @suaveplan/crypto-utils's toBase64Url.
  • Minimum-length big-endian byte derivation — no leading-zero padding.
  • Public-form emits { kty, n, e } only; private-form adds the full CRT set.
  • Maps the canonical qInv field name to JWA's qi per RFC 7517 §6.3.2.

Usage: Basic Example

import { serializeRsaPublicKeyJwk } from "@suaveplan/crypto-rsa";

const jwk = serializeRsaPublicKeyJwk(key);
// { kty: "RSA", n: "...", e: "AQAB" }

Usage: Advanced Example

import {
    parseRsaPrivateKeyJwk,
    serializeRsaPrivateKeyJwk,
} from "@suaveplan/crypto-rsa";

const jwk = serializeRsaPrivateKeyJwk(key);
const roundTripped = parseRsaPrivateKeyJwk(jwk);

API Reference

serializeRsaPublicKeyJwk(key: RsaPublicKey): RsaJwk

Returns { kty: "RSA", n, e }.

serializeRsaPrivateKeyJwk(key: RsaPrivateKey): RsaJwk

Returns { kty: "RSA", n, e, d, p, q, dp, dq, qi }.

Implementation Notes

The minimum-length encoding implies that e === 65537n (the universal default RSA exponent) emits as the 3-byte sequence 0x010001, which base64url-encodes to "AQAB" — the same canonical string every JWK ecosystem produces. Encoding via i2osp with the byte length derived from hex.length / 2 ensures we never accidentally emit a leading-zero byte.