@eryx/crypto/pem Module

JSON

PEM (Privacy-Enhanced Mail) encoding and decoding.

PEM is the standard text format for cryptographic objects such as keys and certificates. A PEM file wraps a base64-encoded DER blob between -----BEGIN <label>----- and -----END <label>----- markers.

This module handles the text-level encoding only - it converts between PEM strings and raw DER buffer values. It does not parse the ASN.1 structure inside the DER. To work with RSA keys specifically, see @eryx/crypto/rsa which provides rsa.private_to_der, etc.

local pem = require("@eryx/crypto/pem")
local rsa = require("@eryx/crypto/rsa")

local priv = rsa.generate_key()

-- Convert PEM -> DER -> PEM (round-trip)
local der   = rsa.private_to_der(priv)
local pemS = pem.encode("RSA PRIVATE KEY", der)
local label, der2 = pem.decode(pemS)
assert(label == "RSA PRIVATE KEY")

Summary

Functions

pem.encode(label: string, data: buffer)string
pem.decode(pemStr: string)(string, buffer)
pem.decodeAll(pemStr: string){ { label: string, data: buffer } }

API Reference

Functions

pem.encode

Wraps raw DER bytes in a PEM block with the given label.

The output follows RFC 7468: base64-encoded content is line-wrapped at 64 characters, with -----BEGIN <label>----- and -----END <label>----- header/footer lines.

Common labels: "RSA PRIVATE KEY", "PUBLIC KEY", "CERTIFICATE", "CERTIFICATE REQUEST".

local pemS = pem.encode("PUBLIC KEY", derBytes)
-- "-----BEGIN PUBLIC KEY-----\nMIIB...\n-----END PUBLIC KEY-----\n"
pem.encode(label: string, data: buffer)string

Parameters

label: string

The PEM label (the text that appears between the dashes).

data: buffer

Raw DER bytes to encode.

Returns

string

PEM-formatted string.

pem.decode

Decodes the first PEM block found in pemStr and returns its label and raw DER bytes.

Whitespace inside the base64 body (including CRLF line endings) is ignored. Raises an error if no valid PEM block is found.

local label, der = pem.decode(pemStr)
print(label)  -- e.g. "RSA PRIVATE KEY"
pem.decode(pemStr: string)(string, buffer)

Parameters

pemStr: string

A string containing at least one PEM block.

Returns

string

The label from the BEGIN line.

buffer

Raw DER bytes.

pem.decodeAll

Decodes all PEM blocks found in pemStr and returns them as an array.

Useful when a single file contains multiple certificates or keys (e.g. a CA bundle or a certificate chain).

local blocks = pem.decodeAll(chain_pem)
for _, block in blocks do
    print(block.label, buffer.len(block.data))
end
pem.decodeAll(pemStr: string){ { label: string, data: buffer } }

Parameters

pemStr: string

A string containing one or more PEM blocks.

Returns

{ { label: string, data: buffer } }

Array of decoded PEM blocks.