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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// SPDX-License-Identifier: 0BSD
import { shake128, shake256 } from "npm:@noble/hashes/sha3";
import * as jose from "npm:jose";
import ky from "npm:ky";
import { base16 } from "npm:multiformats/bases/base16";
type HashAlgorithm = "shake128" | "shake256";
// aspe:keyoxide.org:TOICV3SYXNJP7E4P5AOK5DHW44
const asp = await fetchASP("TOICV3SYXNJP7E4P5AOK5DHW44");
console.log("originalUri: aspe:keyoxide.org:TOICV3SYXNJP7E4P5AOK5DHW44");
console.log(processASP(asp, "shake128", 10 * 4 * 4));
console.log(processASP(asp, "shake128", 12 * 4 * 4));
console.log(processASP(asp, "shake128", 14 * 4 * 4));
function processASP(asp: string, alg: HashAlgorithm = "shake128", d = 160) {
let collisionResistance;
if (alg === "shake128") collisionResistance = Math.min(d / 2, 128);
else if (alg === "shake256") collisionResistance = Math.min(d / 2, 256);
const jwk = extractJWK(asp);
const fingerprint = calculateFingerprint(jwk, alg, d);
return {
algorithm: `${alg}; dkLen=${d / 8} (bytes); d=${d} (bits)`,
collisionResistance,
uri: `aspe:${fingerprint}`,
uriWithAuthority: `aspe://keyoxide.org/${fingerprint}`,
fingerprint,
fingerprintLength: fingerprint.length,
formattedFingerprint: formatFingerprint(fingerprint),
keyId: getKeyId(fingerprint),
};
}
function getKeyId(fingerprint: string) {
return formatFingerprint(fingerprint)
.split(" ")
.slice(0, 4)
.join(" ");
}
function formatFingerprint(fingerprint: string) {
return fingerprint
.toUpperCase()
.split(/([0-9A-F]{4})/g)
.filter(Boolean)
.join(" ");
}
function calculateFingerprint(jwk: jose.JWK, alg: HashAlgorithm, d: number) {
const components = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
const data = new TextEncoder().encode(JSON.stringify(components));
let hashFn = shake128;
if (alg === "shake128") {
hashFn = shake128;
} else if (alg === "shake256") {
hashFn = shake256;
} else {
throw new Error("error: unsupported algorithm");
}
const hash = hashFn(data, { dkLen: d / 8 });
return base16.baseEncode(hash);
}
function extractJWK(jwt) {
const { jwk } = jose.decodeProtectedHeader(jwt);
return jwk;
}
function fetchASP(id, server = "keyoxide.org") {
const url = new URL(`https://keyoxide.org/.well-known/aspe/id/${id}`);
url.hostname = server;
return ky.get(url).text();
}