UNPKG

1.26 kBJavaScriptView Raw
1/**
2 * Aes (experimental)
3 * ==================
4 *
5 * Advanced Encryption Standard (Aes). This is a low-level tool for encrypting
6 * or decrypting blocks of data. There is almost never a reason to use this -
7 * don't use it unless you need to encrypt or decrypt individual blocks.
8 */
9'use strict'
10
11import _Aes from 'aes'
12
13class Aes { }
14
15Aes.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
24Aes.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
33Aes.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
47Aes.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
57export { Aes }