1import { X509Certificate, createHash, createPrivateKey, createPublicKey } from "node:crypto";
2import { readFileSync } from "node:fs";
3
4const cert = new X509Certificate(readFileSync("cert.pem")); // PEM or DER
5const publicKey = cert.publicKey; // a KeyObject of type "public"
6
7const spkiPem = publicKey.export({ type: "spki", format: "pem" });
8const spkiDer = publicKey.export({ type: "spki", format: "der" });
9process.stdout.write(spkiPem);
10
11const digest = createHash("sha256").update(spkiDer).digest();
12console.log("SPKI SHA-256:", digest.toString("hex").match(/../g).join(":"));
13console.log("SPKI pin (base64):", digest.toString("base64"));
14
15// Does key.pem belong to this certificate? (checkPrivateKey compares the public halves)
16const privateKey = createPrivateKey(readFileSync("key.pem"));
17console.log("key.pem matches:", cert.checkPrivateKey(privateKey));
18console.log("same key object:", createPublicKey(privateKey).equals(publicKey));
19