forked from ajksdhfueisde/test-ws
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaead.mjs
More file actions
69 lines (58 loc) · 1.31 KB
/
aead.mjs
File metadata and controls
69 lines (58 loc) · 1.31 KB
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
import { createDecipheriv, createCipheriv } from 'crypto'
const keySize = {
'aes-256-gcm': 32,
'chacha20-poly1305': 32
}
const saltSize = {
'aes-256-gcm': 32,
'chacha20-poly1305': 32
}
const nonceSize = {
'aes-256-gcm': 12,
'chacha20-poly1305': 12
}
const tagSize = {
'aes-256-gcm': 16,
'chacha20-poly1305': 16
}
const options = {
'aes-256-gcm': {},
'chacha20-poly1305': { authTagLength: 16 }
}
class AEAD {
constructor (algorithm, key) {
this.algorithm = algorithm
this.key = key
this.nonce = Buffer.alloc(nonceSize[algorithm])
this.options = options[algorithm]
}
decrypt (c, tag) {
const d = createDecipheriv(this.algorithm, this.key, this.nonce, this.options)
const m = []
m.push(d.setAuthTag(tag).update(c))
try {
m.push(d.final())
this.incNonce()
return Buffer.concat(m)
} catch (e) {
return null
}
}
encrypt (m) {
const e = createCipheriv(this.algorithm, this.key, this.nonce, this.options)
const c = []
c.push(e.update(m))
c.push(e.final())
c.push(e.getAuthTag())
this.incNonce()
return Buffer.concat(c)
}
incNonce () {
const n = new Uint32Array(this.nonce.buffer)
let i = 0
do {
n[i]++
} while (n[i] === 0 && ++i < n.length)
}
}
export { keySize, saltSize, tagSize, AEAD }