Unverified Commit 5609c373 authored by Hong Minhee's avatar Hong Minhee
Browse files

`importPem()` function

parent 00944b1b
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
.DS_Store
deno.lock
t.ts
t2.ts
+1 −0
Original line number Diff line number Diff line
@@ -12,6 +12,7 @@ To be released.
    [[#209]]

     -  Added `importPkcs1()` function.
     -  Added `importPem()` function.

[#209]: https://github.com/fedify-dev/fedify/issues/209

+12 −0
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@ import {
  exportMultibaseKey,
  exportSpki,
  importMultibaseKey,
  importPem,
  importPkcs1,
  importSpki,
} from "./key.ts";
@@ -101,6 +102,17 @@ test("importPkcs1()", async () => {
  assertEquals(await exportJwk(rsaKey), rsaJwk);
});

test("importPem()", async () => {
  const rsaPkcs1Key = await importPem(rsaPkcs1);
  assertEquals(await exportJwk(rsaPkcs1Key), rsaJwk);

  const rsaSpkiKey = await importPem(rsaSpki);
  assertEquals(await exportJwk(rsaSpkiKey), rsaJwk);

  const ed25519Key = await importPem(ed25519Pem);
  assertEquals(await exportJwk(ed25519Key), ed25519Jwk);
});

test("importMultibase()", async () => {
  const rsaKey = await importMultibaseKey(rsaMultibase);
  assertEquals(await exportJwk(rsaKey), rsaJwk);
+13 −0
Original line number Diff line number Diff line
@@ -78,6 +78,19 @@ export function importPkcs1(pem: string): Promise<CryptoKey> {
  return importSpki(spki);
}

const PKCS1_HEADER = /^\s*-----BEGIN\s+RSA\s+PUBLIC\s+KEY-----\s*\n/;

/**
 * Imports a PEM formatted public key (SPKI or PKCS#1).
 * @param pem The PEM formatted public key to import (SPKI or PKCS#1).
 * @returns The imported public key.
 * @throws {TypeError} If the key is invalid or unsupported.
 * @since 1.5.0
 */
export function importPem(pem: string): Promise<CryptoKey> {
  return PKCS1_HEADER.test(pem) ? importPkcs1(pem) : importSpki(pem);
}

/**
 * Imports a [Multibase]-encoded public key.
 *