-
Notifications
You must be signed in to change notification settings - Fork 1
/
ecdsa256.ts
113 lines (102 loc) · 2.47 KB
/
ecdsa256.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import {getRandomValues, subtle} from './crypto'
import {
bufferFromString,
stringFromBuffer,
base64urlFromString,
stringFromBase64Url,
concatBuffers
} from './buffers'
/** ECDSA256 attestation */
export interface ECDSA256Attestation {
id: string
response: {
signature: string
authenticatorDataBytes: string
clientDataJson: string
}
}
/** Get ECDSA256 attestation */
export async function getECDSA256Attestation(
challenge: string,
identifier: string,
key: string
): Promise<ECDSA256Attestation> {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const authenticatorData = new Uint8Array(10)
getRandomValues(authenticatorData)
const clientData = {
type: 'webauthn.get',
origin: window.location.origin,
challenge
}
const clientDataBytes = bufferFromString(JSON.stringify(clientData))
const clientDataBytesHash = await subtle.digest('SHA-256', clientDataBytes)
const signatureData = concatBuffers(
new Uint8Array(authenticatorData),
new Uint8Array(clientDataBytesHash)
)
const privateKeyPortable = bufferFromString(stringFromBase64Url(key))
const privateKey = await subtle.importKey(
'pkcs8',
privateKeyPortable,
{
name: 'ECDSA',
namedCurve: 'P-256'
},
true,
['sign']
)
const signature = await subtle.sign(
{
name: 'ECDSA',
hash: 'SHA-256'
},
privateKey,
signatureData
)
return {
id: identifier,
response: {
signature: base64urlFromString(stringFromBuffer(signature)),
authenticatorDataBytes: base64urlFromString(
stringFromBuffer(authenticatorData)
),
clientDataJson: base64urlFromString(stringFromBuffer(clientDataBytes))
}
}
}
/** ECDSA256 key */
export interface ECDSA256Key {
privateKey: string
publicKey: {
x: string
y: string
}
}
/** Get ECDSA256 key */
export async function generateECDSA256Key(): Promise<ECDSA256Key> {
const {privateKey: privateKey, publicKey: publicKey} =
await subtle.generateKey(
{
name: 'ECDSA',
namedCurve: 'P-256'
},
true,
['sign', 'verify']
)
const privateKeyBuffer = await subtle.exportKey(
'pkcs8',
privateKey as CryptoKey
)
const privateKeyString = base64urlFromString(
stringFromBuffer(privateKeyBuffer)
)
const {x, y} = await subtle.exportKey('jwk', publicKey as CryptoKey)
return {
privateKey: privateKeyString,
publicKey: {
x: x || '',
y: y || ''
}
}
}