forked from ethereumjs/ethereumjs-monorepo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmac.ts
37 lines (30 loc) · 982 Bytes
/
mac.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
import { createCipheriv } from 'crypto'
import { keccak256 } from 'ethereum-cryptography/keccak.js'
import { xor } from '../util.js'
type Hash = ReturnType<typeof keccak256.create>
export class MAC {
protected _hash: Hash
protected _secret: Uint8Array
constructor(secret: Uint8Array) {
this._hash = keccak256.create()
this._secret = secret
}
update(data: Uint8Array | string) {
this._hash.update(data)
}
updateHeader(data: Uint8Array | string) {
const aes = createCipheriv('aes-256-ecb', this._secret, '')
const encrypted = aes.update(this.digest())
this._hash.update(xor(encrypted, data))
}
updateBody(data: Uint8Array | string) {
this._hash.update(data)
const prev = this.digest()
const aes = createCipheriv('aes-256-ecb', this._secret, '')
const encrypted = aes.update(prev)
this._hash.update(xor(encrypted, prev))
}
digest() {
return Uint8Array.from(this._hash.clone().digest().subarray(0, 16))
}
}