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
// SPDX-License-Identifier: 0BSD
import { varint } from "npm:multiformats";
import { base58btc } from "npm:multiformats/bases/base58";
const KeyType = {
"P-256": { name: "P-256", byteSize: 256 / 8 + 1 },
"P-384": { name: "P-384", byteSize: 384 / 8 + 1 },
"secp256k1": { name: "secp256k1", byteSize: 256 / 8 + 1 },
"X25519": { name: "X25519", byteSize: 32 },
"Ed25519": { name: "Ed25519", byteSize: 32 },
"JWK-JCS": { name: "JWK-JCS" },
} as const;
const Codec = {
0x1200: KeyType["P-256"],
0x1201: KeyType["P-384"],
0xe7: KeyType["secp256k1"],
0xec: KeyType["X25519"],
0xed: KeyType["Ed25519"],
0xeb51: KeyType["JWK-JCS"],
} as const;
export function multibaseToBytes(input: string) {
const bytes = base58btc.decode(input);
const [codec, prefixLength] = varint.decode(bytes);
const keyType = Codec[codec];
if (!keyType) throw new TypeError("error: unsupported key type");
const keyBytes = bytes.slice(prefixLength);
if ("byteSize" in keyType && (keyBytes.length !== keyType.byteSize)) {
throw new Error("error: invalid key size");
}
return { keyBytes, keyType: keyType.name };
}
export function bytesToMultibase(keyBytes: Uint8Array, keyType: string) {
const type = KeyType[keyType];
if (!type) throw new TypeError("error: unsupported key type");
if ("byteSize" in type && (keyBytes.length !== type.byteSize)) {
throw new Error("error: invalid key size");
}
const [codecCode] = Object.entries(Codec).find(([, keyType]) => keyType === type);
const codec = parseInt(codecCode, 10);
const prefixLength = varint.encodingLength(codec);
const bytes = new Uint8Array(prefixLength + keyBytes.length);
varint.encodeTo(codec, bytes);
bytes.set(keyBytes, prefixLength);
return base58btc.encode(bytes);
}
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