forked from passwordless-id/webauthn
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.ts
64 lines (48 loc) · 1.66 KB
/
utils.ts
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
/********************************
Encoding/Decoding Utils
********************************/
/*
let webCrypto :any = null
export async function getCrypto() {
if(!webCrypto) {
console.log(window?.crypto)
webCrypto = window?.crypto ?? (await import("crypto")).webcrypto
console.log(webCrypto)
}
return webCrypto
}
*/
export function randomChallenge() {
return crypto.randomUUID()
}
export function toBuffer(txt :string) :ArrayBuffer {
return Uint8Array.from(txt, c => c.charCodeAt(0)).buffer
}
export function parseBuffer(buffer :ArrayBuffer) :string {
return String.fromCharCode(...new Uint8Array(buffer))
}
export function isBase64url(txt :string) :boolean {
return txt.match(/^[a-zA-Z0-9\-_]+=*$/) !== null
}
export function toBase64url(buffer :ArrayBuffer) :string {
const txt = btoa(parseBuffer(buffer)) // base64
return txt.replaceAll('+', '-').replaceAll('/', '_')
}
export function parseBase64url(txt :string) :ArrayBuffer {
txt = txt.replaceAll('-', '+').replaceAll('_', '/') // base64url -> base64
return toBuffer(atob(txt))
}
export async function sha256(buffer :ArrayBuffer) :Promise<ArrayBuffer> {
return await crypto.subtle.digest('SHA-256', buffer)
}
export function bufferToHex (buffer :ArrayBuffer) :string {
return [...new Uint8Array (buffer)]
.map (b => b.toString (16).padStart (2, "0"))
.join ("");
}
export function concatenateBuffers(buffer1 :ArrayBuffer, buffer2 :ArrayBuffer) {
var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
tmp.set(new Uint8Array(buffer1), 0);
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
return tmp;
};