1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | 'use strict'
|
10 |
|
11 | import _Aes from 'aes'
|
12 |
|
13 | class Aes { }
|
14 |
|
15 | Aes.encrypt = function (messageBuf, keyBuf) {
|
16 | const key = Aes.buf2Words(keyBuf)
|
17 | const message = Aes.buf2Words(messageBuf)
|
18 | const a = new _Aes(key)
|
19 | const enc = a.encrypt(message)
|
20 | const encBuf = Aes.words2Buf(enc)
|
21 | return encBuf
|
22 | }
|
23 |
|
24 | Aes.decrypt = function (encBuf, keyBuf) {
|
25 | const enc = Aes.buf2Words(encBuf)
|
26 | const key = Aes.buf2Words(keyBuf)
|
27 | const a = new _Aes(key)
|
28 | const message = a.decrypt(enc)
|
29 | const messageBuf = Aes.words2Buf(message)
|
30 | return messageBuf
|
31 | }
|
32 |
|
33 | Aes.buf2Words = function (buf) {
|
34 | if (buf.length % 4) {
|
35 | throw new Error('buf length must be a multiple of 4')
|
36 | }
|
37 |
|
38 | const words = []
|
39 |
|
40 | for (let i = 0; i < buf.length / 4; i++) {
|
41 | words.push(buf.readUInt32BE(i * 4))
|
42 | }
|
43 |
|
44 | return words
|
45 | }
|
46 |
|
47 | Aes.words2Buf = function (words) {
|
48 | const buf = Buffer.alloc(words.length * 4)
|
49 |
|
50 | for (let i = 0; i < words.length; i++) {
|
51 | buf.writeUInt32BE(words[i], i * 4)
|
52 | }
|
53 |
|
54 | return buf
|
55 | }
|
56 |
|
57 | export { Aes }
|