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

53 lines
1.5 KiB
Markdown

# `keys/serialize-pkcs1-private`
## Purpose
Inverse of `parseRsaPrivateKeyPkcs1`. Emits a DER `RSAPrivateKey` SEQUENCE
per RFC 8017 Appendix A.1.2 from a canonical `RsaPrivateKey`. Always emits
two-prime form with `version 0`. Multi-prime keys cannot be constructed
through this package's parsers (the parser rejects them) so the serialiser
also never has to emit the multi-prime branch.
## Features
- Strict-DER nine-INTEGER SEQUENCE emission in canonical field order.
- Always emits `version 0` (two-prime).
- Pure function — no validation overhead.
## Usage: Basic Example
```ts
import { serializeRsaPrivateKeyPkcs1 } from "@suaveplan/crypto-rsa";
const der = serializeRsaPrivateKeyPkcs1(key);
```
## Usage: Advanced Example
```ts
import {
parseRsaPrivateKeyPkcs1,
serializeRsaPrivateKeyPkcs1,
} from "@suaveplan/crypto-rsa";
const roundTripped = parseRsaPrivateKeyPkcs1(
serializeRsaPrivateKeyPkcs1(key)
);
```
## API Reference
### `serializeRsaPrivateKeyPkcs1(key: RsaPrivateKey): Uint8Array`
Returns the canonical DER encoding.
## Implementation Notes
The field order matches RFC 8017 Appendix A.1.2 exactly: `version`,
`modulus`, `publicExponent`, `privateExponent`, `prime1`, `prime2`,
`exponent1`, `exponent2`, `coefficient`. Any reorder would still parse
under a tolerant reader but would fail strict-DER validation.
`version` is encoded as `0n` rather than `0` (a `bigint`) because
`encodeInteger` is monomorphised over `bigint` for the two-prime case.