-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (38 loc) · 1 KB
/
index.js
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
/**
* Created by nilptr on 16/2/29.
*/
function PKCS7(k) {
if (!(this instanceof PKCS7))
return new PKCS7(k);
if (k < 1 || k > 255)
throw new TypeError('invalid k: k < 1 or k > 255');
this.blockSize = k;
}
PKCS7.prototype.pad = function (buf) {
var blockSize = this.blockSize;
var bufLen = buf.length;
var padLen = blockSize - (bufLen % blockSize);
var padding = new Buffer(padLen).fill(padLen);
return Buffer.concat([buf, padding]);
};
/**
* returns a new Buffer without pkcs#7 padding
*
* @param {Buffer} buf
* @returns {*}
*/
PKCS7.prototype.unpad = function (buf) {
// check length
var blockSize = this.blockSize;
var bufLen = buf.length;
if (bufLen % blockSize !== 0)
throw new Error('invalid buffer');
// check padding
var padLen = buf[bufLen - 1];
var padding = buf.slice(bufLen - padLen);
for (var i = 0; i < padLen; ++i)
if (padding[i] !== padLen)
throw new Error('invalid buffer');
return buf.slice(0, bufLen - padLen);
};
module.exports = PKCS7;