UNPKG

1.94 kBJavaScriptView Raw
1import { arrbufs } from "../common/index.js";
2import { KeyType } from "./types.js";
3export const EDWARDS_DID_PREFIX = new Uint8Array([0xed, 0x01]);
4export const BLS_DID_PREFIX = new Uint8Array([0xea, 0x01]);
5export const RSA_DID_PREFIX = new Uint8Array([0x00, 0xf5, 0x02]);
6export const BASE58_DID_PREFIX = 'did:key:z';
7/**
8 * Magic bytes.
9 */
10export function magicBytes(keyType) {
11 switch (keyType) {
12 case KeyType.Edwards: return EDWARDS_DID_PREFIX;
13 case KeyType.RSA: return RSA_DID_PREFIX;
14 case KeyType.BLS: return BLS_DID_PREFIX;
15 default: return null;
16 }
17}
18/**
19 * Parse magic bytes on prefixed key-buffer
20 * to determine cryptosystem & the unprefixed key-buffer.
21 */
22export const parseMagicBytes = (prefixedKey) => {
23 // RSA
24 if (hasPrefix(prefixedKey, RSA_DID_PREFIX)) {
25 return {
26 keyBuffer: prefixedKey.slice(RSA_DID_PREFIX.byteLength),
27 type: KeyType.RSA
28 };
29 // EDWARDS
30 }
31 else if (hasPrefix(prefixedKey, EDWARDS_DID_PREFIX)) {
32 return {
33 keyBuffer: prefixedKey.slice(EDWARDS_DID_PREFIX.byteLength),
34 type: KeyType.Edwards
35 };
36 // BLS
37 }
38 else if (hasPrefix(prefixedKey, BLS_DID_PREFIX)) {
39 return {
40 keyBuffer: prefixedKey.slice(BLS_DID_PREFIX.byteLength),
41 type: KeyType.BLS
42 };
43 }
44 throw new Error("Unsupported key algorithm. Try using RSA.");
45};
46/**
47 * Determines if an ArrayBuffer has a given indeterminate length-prefix.
48 */
49export const hasPrefix = (prefixedKey, prefix) => {
50 return arrbufs.equal(prefix, prefixedKey.slice(0, prefix.byteLength));
51};
52export const toKeyType = (str) => {
53 switch (str) {
54 case 'rsa': return KeyType.RSA;
55 case 'ed25519': return KeyType.Edwards;
56 case 'bls12-381': return KeyType.BLS;
57 }
58 throw new Error(`Key Type ${str} not supported`);
59};
60//# sourceMappingURL=util.js.map
\No newline at end of file