Public
Script
April 16, 2024
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import { compressPoint } from "https://esm.town/v/vladimyr/libec";
import { bytesToMultibase, multibaseToBytes } from "https://esm.town/v/vladimyr/libmultibase";
import jcs from "npm:canonicalize";
import { base64url } from "npm:multiformats/bases/base64";
// @see: https://datatracker.ietf.org/doc/html/rfc7517#appendix-A.1
const jwk = {
kty: "EC",
crv: "P-256",
x: "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4",
y: "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM",
};
const compressed = compressPoint({
x: base64url.baseDecode(jwk.x),
y: base64url.baseDecode(jwk.y),
});
const publicKeyMultibase1 = bytesToMultibase(compressed, jwk.crv);
console.log(publicKeyMultibase1);
// ==> zDnaekw6iisW1j4ronMuZagbvVehJK4unit6kvZ8UqJ2LSG1j
// @see: https://dev.uniresolver.io/#did:key:zDnaekw6iisW1j4ronMuZagbvVehJK4unit6kvZ8UqJ2LSG1j
const canonicalizedJWK = jcs(jwk);
console.log(canonicalizedJWK);
// ==> {"crv":"P-256","kty":"EC","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}
const bytes = new TextEncoder().encode(canonicalizedJWK);
const publicKeyMultibase2 = bytesToMultibase(bytes, "JWK-JCS");
console.log(publicKeyMultibase2);
// ==> z2dmzD81cgPx8Vki7JbuuMmFYrWPgYoytykUZ3eyqht1j9Kbpeg3mYxvgF8UxoyX9dknsQJGitBcaBSeP1eLn2Gj2VQ78Fx565Mphyk52rAZK1iNbPHLaYtG9aAvnwNoHjNgC4Tkr8X1QShmGkmCtGrD9GpYULfUMTivZsCkPLeDWnjXwA
const extractedJWK = JSON.parse(
new TextDecoder().decode(
multibaseToBytes(publicKeyMultibase2).keyBytes,
),
);
console.log(JSON.stringify(extractedJWK));
// ==> {"crv":"P-256","kty":"EC","x":"MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4","y":"4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM"}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
April 16, 2024