UNPKG

2.46 kBJavaScriptView Raw
1/**
2 * otplib-utils
3 *
4 * @author Gerald Yeo <contact@fusedthought.com>
5 * @version: 7.0.0
6 * @license: MIT
7 **/
8'use strict';
9
10Object.defineProperty(exports, '__esModule', { value: true });
11
12function hexToInt(hex) {
13 return parseInt(hex, 16);
14}
15
16function intToHex(value) {
17 return parseInt(value, 10).toString(16);
18}
19
20function isSameToken(token1, token2) {
21 return parseFloat(token1) === parseFloat(token2);
22}
23
24function leftPad(value, length) {
25 var total = !length ? 0 : length;
26 var padded = value + '';
27 while (padded.length < total) {
28 padded = '0' + padded;
29 }
30 return padded;
31}
32
33function padSecret(secretBuffer, size, encoding) {
34 var secret = secretBuffer.toString(encoding);
35 var len = secret.length;
36 if (size && len < size) {
37 var newSecret = new Array(size - len + 1).join(secretBuffer.toString('hex'));
38 return new Buffer(newSecret, 'hex').slice(0, size);
39 }
40 return secretBuffer;
41}
42
43function removeSpaces() {
44 var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
45
46 if (value == null) {
47 return '';
48 }
49 return value.replace(/\s+/g, '');
50}
51
52function secretKey(length) {
53 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
54
55 if (!length || length < 1) {
56 return '';
57 }
58 if (!options.crypto || typeof options.crypto.randomBytes !== 'function') {
59 throw new Error('Expecting options.crypto to have a randomBytes function');
60 }
61 return options.crypto.randomBytes(length).toString('base64').slice(0, length);
62}
63
64function setsOf(value) {
65 var amount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;
66 var divider = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ' ';
67
68 var num = parseInt(amount, 10);
69 if (Number.isNaN(num) || typeof value !== 'string') {
70 return '';
71 }
72 var regex = new RegExp('.{1,' + amount + '}', 'g');
73 return value.match(regex).join(divider);
74}
75
76function stringToHex(value) {
77 var val = value == null ? '' : value;
78 var hex = '';
79 var tmp = '';
80 for (var i = 0; i < val.length; i++) {
81 tmp = ('0000' + val.charCodeAt(i).toString(16)).slice(-2);
82 hex += '' + tmp;
83 }
84 return hex;
85}
86
87exports.hexToInt = hexToInt;
88exports.intToHex = intToHex;
89exports.isSameToken = isSameToken;
90exports.leftPad = leftPad;
91exports.padSecret = padSecret;
92exports.removeSpaces = removeSpaces;
93exports.secretKey = secretKey;
94exports.setsOf = setsOf;
95exports.stringToHex = stringToHex;
\No newline at end of file