-
Notifications
You must be signed in to change notification settings - Fork 35
/
sign-url-data.ts
51 lines (43 loc) · 1.47 KB
/
sign-url-data.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
import { base64url } from '@scure/base'
import { getPublicKey } from 'ethereum-cryptography/secp256k1'
import { bytesToHex } from 'ethereum-cryptography/utils'
import { deserializePublicKey } from './deserialize-public-key'
import {
decodeVerificationURLHash,
encodeVerificationURLHash,
} from './encode-url-hash'
import { serializePublicKey } from './serialize-public-key'
import { signData, verifySignedData } from './sign-data'
import type { EncodedURLData } from './encode-url-data'
import type { EncodedVerificationURLHash } from './encode-url-hash'
export async function signEncodedURLData(
encodedURLData: EncodedURLData,
privateKey: Uint8Array | string
): Promise<EncodedVerificationURLHash> {
const signature = await signData(encodedURLData, privateKey)
const encodedSignature = base64url.encode(signature)
const serializedPublicKey = serializePublicKey(
`0x${bytesToHex(getPublicKey(privateKey))}`
)
return encodeVerificationURLHash({
signature: encodedSignature,
publicKey: serializedPublicKey,
})
}
export function verifyEncodedURLData(
encodedURLData: string,
encodedVerificationURLHash: string
): boolean {
const { signature, publicKey } = decodeVerificationURLHash(
encodedVerificationURLHash
)
const decodedSignature = base64url.decode(signature)
const deserializedPublicKey = deserializePublicKey(publicKey, {
compress: false,
})
return verifySignedData(
decodedSignature,
encodedURLData,
deserializedPublicKey
)
}