/
crypto.test.ts
91 lines (74 loc) · 2.13 KB
/
crypto.test.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
import { EdgeVM } from '../../src'
import { createHash } from 'crypto'
const [NODE_MAJOR] = process.versions.node.split('.').map((v) => Number(v))
test('crypto.subtle.digest returns an ArrayBuffer', async () => {
const vm = new EdgeVM()
async function fn() {
const digest = await crypto.subtle.digest(
'SHA-256',
crypto.getRandomValues(new Uint8Array(32))
)
return digest
}
const fromContext = vm.evaluate(`({ ArrayBuffer })`)
const digest = await vm.evaluate(`(${fn})()`)
expect(digest).toBeInstanceOf(fromContext.ArrayBuffer)
})
test('crypto.subtle.digest returns a SHA-256 hash', async () => {
const vm = new EdgeVM()
async function fn() {
const digest = await crypto.subtle.digest(
'SHA-256',
new Uint8Array([104, 105, 33])
)
return digest
}
const digest = await vm.evaluate(`(${fn})()`)
expect(toHex(digest)).toEqual(
createHash('sha256').update('hi!').digest('hex')
)
})
function toHex(buffer: ArrayBuffer) {
return Array.from(new Uint8Array(buffer))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
test('crypto.generateKey works with a Uint8Array from the VM', async () => {
async function fn() {
await crypto.subtle.generateKey(
{
name: 'RSA-PSS',
hash: 'SHA-256',
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
modulusLength: 2048,
},
false,
['sign', 'verify']
)
}
const vm = new EdgeVM()
await vm.evaluate(`(${fn})()`)
})
if (NODE_MAJOR >= 16) {
test('Ed25519', async () => {
const vm = new EdgeVM()
function fn() {
return crypto.subtle.generateKey('Ed25519', false, ['sign', 'verify'])
}
const kp = await vm.evaluate(`(${fn})()`)
expect(kp).toHaveProperty('privateKey')
expect(kp).toHaveProperty('publicKey')
})
test('X25519', async () => {
const vm = new EdgeVM()
function fn() {
return crypto.subtle.generateKey('X25519', false, [
'deriveBits',
'deriveKey',
])
}
const kp = await vm.evaluate(`(${fn})()`)
expect(kp).toHaveProperty('privateKey')
expect(kp).toHaveProperty('publicKey')
})
}