@localnerve/hmac-symmetric 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.json +15 -0
- package/LICENSE.md +11 -0
- package/README.md +76 -0
- package/babel.config.json +11 -0
- package/cjs/errors.cjs +30 -0
- package/cjs/helpers.cjs +45 -0
- package/cjs/index.cjs +37 -0
- package/cjs/utils.cjs +108 -0
- package/jest.config.js +10 -0
- package/lib/errors.js +23 -0
- package/lib/helpers.js +38 -0
- package/lib/index.js +8 -0
- package/lib/utils.js +114 -0
- package/package.json +59 -0
- package/posttranspile.js +13 -0
package/.eslintrc.json
ADDED
package/LICENSE.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Copyright 2023 Alex Grant, LocalNerve, LLC
|
|
2
|
+
|
|
3
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
4
|
+
|
|
5
|
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
6
|
+
|
|
7
|
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
8
|
+
|
|
9
|
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
10
|
+
|
|
11
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
package/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# hmac-symmetric
|
|
2
|
+
|
|
3
|
+
> A library for simple symmetric encryption with HMAC digests
|
|
4
|
+
|
|
5
|
+
[](https://badge.fury.io/js/@localnerve%2Fhmac-symmetric)
|
|
6
|
+

|
|
7
|
+
[](https://coveralls.io/github/localnerve/hmac-symmetric?branch=main)
|
|
8
|
+
|
|
9
|
+
## Summary
|
|
10
|
+
A zero dependency node library with basic functions for using symmetric encryption with HMAC digests. A a simple, small, configurable, and reusable set of functions for payload integrity and authentication.
|
|
11
|
+
|
|
12
|
+
## Applications
|
|
13
|
+
This is a general purpose library that can be used in any application where an HMAC'd symmetrically encrypted payload is useful. Here's a quick reminder of a couple of useful applications for this library:
|
|
14
|
+
1. Bot Mitigation
|
|
15
|
+
When the payload is a simple timestamp, roundtripping (get at the beginning and send at the end of input) can be used to force bots to take a "human" amount of time to submit a form or field. This is a deal breaker for any serious bot network. In my experience, this is the biggest step you can take to destroy bots and maintain user trust, but you have to procure/measure an accurate minimum human usage time.
|
|
16
|
+
2. Integrity and Authenticity
|
|
17
|
+
The base function of a hashcode is to ensure payload integrity (that it has been unaltered). When combined with a shared secret (HMAC), this also ensures authtenticity. If there are services on your network that will receive a data block that originated from the a trusted source, this can be used to verify the integrity and authenticity of that data block, no matter how many hands it went through in between.
|
|
18
|
+
|
|
19
|
+
## API
|
|
20
|
+
This library uses the environment variables
|
|
21
|
+
+ `HS_HMAC_SECRET`
|
|
22
|
+
+ `HS_ENCRYPTION_KEY`
|
|
23
|
+
|
|
24
|
+
As the default source for keys for cryptographic functions.
|
|
25
|
+
Overridable in the options.
|
|
26
|
+
|
|
27
|
+
Methods this library exports:
|
|
28
|
+
|
|
29
|
+
### encryptAndDigest
|
|
30
|
+
Symmetrically encrypt data and generate an HMAC digest for it.
|
|
31
|
+
`encryptAndDigest (input [, options]) : { payload, digest }`
|
|
32
|
+
* {String|Buffer|TypedArray|DataView} input - The data to encrypt
|
|
33
|
+
* {Object} [options] - Optional options for [generateHmac](#generatehmac) and [symmetricEncrypt](#symmetricencrypt)
|
|
34
|
+
* Returns {Object} with `payload` and `digest` properties for the encrypted payload and the hmac digest.
|
|
35
|
+
|
|
36
|
+
### decryptAndTest
|
|
37
|
+
Symmetrically decrypt data and test it's HMAC digest against an original.
|
|
38
|
+
`decryptAndTest (originalDigest, encryptedInput [, options]) : { ok, decrypted }`
|
|
39
|
+
* {String} originalDigest - The original hmac digest to test against.
|
|
40
|
+
* {String} encryptedInput - The encrypted input data string.
|
|
41
|
+
* {Object} [options] - Optional options for [generateHmac](#generatehmac) and [symmetricDecrypt](#symmetricdecrypt)
|
|
42
|
+
* Returns {Object} with `ok` and `decrypted` properties for the test result and the decrypted payload.
|
|
43
|
+
|
|
44
|
+
### generateHmac
|
|
45
|
+
Generate an HMAC digest using the HMAC secret.
|
|
46
|
+
`generateHmac (input [, options]) : String`
|
|
47
|
+
* {String|Buffer|TypedArray|DataView} input - Input data.
|
|
48
|
+
* {Object} [options] - Optional options.
|
|
49
|
+
* {String} [options.inputEncoding] - Applied if input is a String. Default 'utf8'.
|
|
50
|
+
* {String} [options.hmacAlgo] - Algo used to create HMAC. Default 'sha256'.
|
|
51
|
+
* {String} [options.hmacSecret] - Secret to use. Defaults to environment variable `HS_HMAC_SECRET`.
|
|
52
|
+
* Returns {String} of a hex encoded HMAC digest.
|
|
53
|
+
|
|
54
|
+
### symmetricEncrypt
|
|
55
|
+
Symmetrically encrypt the input using an encryption key.
|
|
56
|
+
`symmetricEncrypt (input [, options]) : String`
|
|
57
|
+
* {String|Buffer|TypedArray|DataView} input - The data to encrypt.
|
|
58
|
+
* {Object} [options] - Optional options.
|
|
59
|
+
* {String} [options.encryptionAlgo] - Symmetric cipher algo, defaults to 'aes-256-cbc'.
|
|
60
|
+
* {String} [options.encryptionKey] - Symmetric cipher key. Defaults to environment variable `HS_ENCRYPTION_KEY`.
|
|
61
|
+
* {String} [options.inputEncoding] - Encoding if the input is a String. Defaults to 'utf8'.
|
|
62
|
+
* Returns {String} hex encoded encryption of the input.
|
|
63
|
+
|
|
64
|
+
### symmetricDecrypt
|
|
65
|
+
Symmetrically decrypt an encrypted input using an encryption key.
|
|
66
|
+
`symmetricDecrypt (input [, options]) : String`
|
|
67
|
+
* {String} input - The encrypted data.
|
|
68
|
+
* {Object} [options] - Optional options.
|
|
69
|
+
* {String} [options.encryptionAlgo] - Symmetric cipher algo, defaults to 'aes-256-cbc'.
|
|
70
|
+
* {String} [options.encryptionKey] - Symmetric cipher key. Defaults to environment `HS_ENCRYPTION_KEY`.
|
|
71
|
+
* {Boolean} [options.outputBuffer] - true to return the Buffer result, false to convert buffer to string. Defaults to false.
|
|
72
|
+
* Returns {String|Buffer} for the decrypted data as requested.
|
|
73
|
+
|
|
74
|
+
## LICENSE
|
|
75
|
+
|
|
76
|
+
* [BSD 3-Clause, Alex Grant, LocalNerve, LLC](LICENSE.md)
|
package/cjs/errors.cjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.HSError = void 0;
|
|
7
|
+
/**
|
|
8
|
+
* Error type for hmac symmetric.
|
|
9
|
+
*
|
|
10
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
11
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
class HSError extends Error {
|
|
15
|
+
static HSE_HMAC = 'HSE_HMAC';
|
|
16
|
+
static HSE_ENCRYPT = 'HSE_ENCRYPT';
|
|
17
|
+
static HSE_DECRYPT = 'HSE_DECRYPT';
|
|
18
|
+
#hseType;
|
|
19
|
+
get hseType() {
|
|
20
|
+
return this.#hseType;
|
|
21
|
+
}
|
|
22
|
+
constructor(hsErrorType, originalError) {
|
|
23
|
+
super(originalError.message, {
|
|
24
|
+
cause: originalError
|
|
25
|
+
});
|
|
26
|
+
this.#hseType = hsErrorType;
|
|
27
|
+
this.name = 'HSError';
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.HSError = HSError;
|
package/cjs/helpers.cjs
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.decryptAndTest = decryptAndTest;
|
|
7
|
+
exports.encryptAndDigest = encryptAndDigest;
|
|
8
|
+
var _utils = require("./utils.cjs");
|
|
9
|
+
/**
|
|
10
|
+
* Convenience methods for hmac symmetric.
|
|
11
|
+
*
|
|
12
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
13
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Generate hmac and symmetrically encrypted payload.
|
|
18
|
+
*
|
|
19
|
+
* @param {String|Buffer|TypedArray|DataView} input - The data to encrypt.
|
|
20
|
+
* @param {Object} [options] - Optional options, @see utils.js
|
|
21
|
+
* @returns {Object} - { digest, payload } on success, throws HSError on error.
|
|
22
|
+
*/
|
|
23
|
+
function encryptAndDigest(input, options) {
|
|
24
|
+
return {
|
|
25
|
+
digest: (0, _utils.generateHmac)(input, options),
|
|
26
|
+
payload: (0, _utils.symmetricEncrypt)(input, options)
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Decrypt encrypted input and check hmac digest with original.
|
|
32
|
+
*
|
|
33
|
+
* @param {String} originalDigest - The original hmac digest to test against.
|
|
34
|
+
* @param {String} encryptedInput - The encrypted input data string.
|
|
35
|
+
* @param {Object} [options] - Optional options, @see utils.js
|
|
36
|
+
* @returns {Object} - { ok, decrypted } on success, throws HSError on error.
|
|
37
|
+
*/
|
|
38
|
+
function decryptAndTest(originalDigest, encryptedInput, options) {
|
|
39
|
+
const decrypted = (0, _utils.symmetricDecrypt)(encryptedInput, options);
|
|
40
|
+
const digest = (0, _utils.generateHmac)(decrypted);
|
|
41
|
+
return {
|
|
42
|
+
ok: digest === originalDigest,
|
|
43
|
+
decrypted
|
|
44
|
+
};
|
|
45
|
+
}
|
package/cjs/index.cjs
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
Object.defineProperty(exports, "decryptAndTest", {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
get: function () {
|
|
9
|
+
return _helpers.decryptAndTest;
|
|
10
|
+
}
|
|
11
|
+
});
|
|
12
|
+
Object.defineProperty(exports, "encryptAndDigest", {
|
|
13
|
+
enumerable: true,
|
|
14
|
+
get: function () {
|
|
15
|
+
return _helpers.encryptAndDigest;
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
Object.defineProperty(exports, "generateHmac", {
|
|
19
|
+
enumerable: true,
|
|
20
|
+
get: function () {
|
|
21
|
+
return _utils.generateHmac;
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
Object.defineProperty(exports, "symmetricDecrypt", {
|
|
25
|
+
enumerable: true,
|
|
26
|
+
get: function () {
|
|
27
|
+
return _utils.symmetricDecrypt;
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
Object.defineProperty(exports, "symmetricEncrypt", {
|
|
31
|
+
enumerable: true,
|
|
32
|
+
get: function () {
|
|
33
|
+
return _utils.symmetricEncrypt;
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
var _utils = require("./utils.cjs");
|
|
37
|
+
var _helpers = require("./helpers.cjs");
|
package/cjs/utils.cjs
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.generateHmac = generateHmac;
|
|
7
|
+
exports.symmetricDecrypt = symmetricDecrypt;
|
|
8
|
+
exports.symmetricEncrypt = symmetricEncrypt;
|
|
9
|
+
var _nodeCrypto = _interopRequireDefault(require("node:crypto"));
|
|
10
|
+
var _errors = require("./errors.cjs");
|
|
11
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
12
|
+
/**
|
|
13
|
+
* hmac and symmetric encryption utility methods.
|
|
14
|
+
* sha256 hmac, aes-256-cbc symmetric encryption.
|
|
15
|
+
*
|
|
16
|
+
* Relies on the following environment:
|
|
17
|
+
* process.env.HS_ENCRYPTION_KEY
|
|
18
|
+
* process.env.HS_HMAC_SECRET
|
|
19
|
+
*
|
|
20
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
21
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Generate an HMAC digest using the HMAC secret.
|
|
26
|
+
*
|
|
27
|
+
* @param {String|Buffer|TypedArray|DataView} input - Input data.
|
|
28
|
+
* @param {Object} [options] - Optional options.
|
|
29
|
+
* @param {String} [options.inputEncoding] - Applied if input is String. Default 'utf8'.
|
|
30
|
+
* @param {String} [options.hmacAlgo] - Algo used to create HMAC. Default 'sha256'.
|
|
31
|
+
* @param {String} [options.hmacSecret] - Secret to use. Defaults to environment HS_HMAC_SECRET.
|
|
32
|
+
* @returns {String} Hmac digest as hex string.
|
|
33
|
+
*/
|
|
34
|
+
function generateHmac(input, {
|
|
35
|
+
inputEncoding = 'utf8',
|
|
36
|
+
hmacAlgo = 'sha256',
|
|
37
|
+
hmacSecret = undefined
|
|
38
|
+
} = {}) {
|
|
39
|
+
let hmacDigest;
|
|
40
|
+
try {
|
|
41
|
+
const hmac = _nodeCrypto.default.createHmac(hmacAlgo, hmacSecret ?? process.env.HS_HMAC_SECRET);
|
|
42
|
+
hmac.update(input, inputEncoding);
|
|
43
|
+
hmacDigest = hmac.digest('hex').toString();
|
|
44
|
+
} catch (e) {
|
|
45
|
+
throw new _errors.HSError(_errors.HSError.HSE_HMAC, e);
|
|
46
|
+
}
|
|
47
|
+
return hmacDigest;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Symmetrically encrypt the input using the shared encryption key.
|
|
52
|
+
*
|
|
53
|
+
* @param {String|Buffer|TypedArray|DataView} input - The data to encrypt.
|
|
54
|
+
* @param {Object} [options] - Optional options.
|
|
55
|
+
* @param {String} [options.encryptionAlgo] - Symmetric cipher algo, defaults to 'aes-256-cbc'.
|
|
56
|
+
* @param {String} [options.encryptionKey] - Symmetric cipher key. Defaults to environment HS_ENCRYPTION_KEY.
|
|
57
|
+
* @param {String} [options.inputEncoding] - Encoding if the input is a String. Defaults to 'utf8'.
|
|
58
|
+
* @returns {String} Hex encoded encrypted string of the input
|
|
59
|
+
*/
|
|
60
|
+
function symmetricEncrypt(input, {
|
|
61
|
+
encryptionAlgo = 'aes-256-cbc',
|
|
62
|
+
encryptionKey = undefined,
|
|
63
|
+
inputEncoding = 'utf8'
|
|
64
|
+
} = {}) {
|
|
65
|
+
let encryptionString;
|
|
66
|
+
try {
|
|
67
|
+
const iv = _nodeCrypto.default.randomBytes(16);
|
|
68
|
+
const key = Buffer.from(encryptionKey ?? process.env.HS_ENCRYPTION_KEY, 'hex');
|
|
69
|
+
const cipher = _nodeCrypto.default.createCipheriv(encryptionAlgo, key, iv);
|
|
70
|
+
let encrypted = cipher.update(input, inputEncoding);
|
|
71
|
+
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
|
72
|
+
encryptionString = `${iv.toString('hex')}:${encrypted.toString('hex')}`;
|
|
73
|
+
} catch (e) {
|
|
74
|
+
throw new _errors.HSError(_errors.HSError.HSE_ENCRYPT, e);
|
|
75
|
+
}
|
|
76
|
+
return encryptionString;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Symmetrically decrypt the ecrypted input using the shared encryption key.
|
|
81
|
+
*
|
|
82
|
+
* @param {String} input - The encrypted data.
|
|
83
|
+
* @param {Object} [options] - Optional options.
|
|
84
|
+
* @param {String} [options.encryptionAlgo] - Symmetric cipher algo, defaults to 'aes-256-cbc'.
|
|
85
|
+
* @param {String} [options.encryptionKey] - Symmetric cipher key. Defaults to environment HS_ENCRYPTION_KEY.
|
|
86
|
+
* @param {Boolean} [options.outputBuffer] - true to return the Buffer result, false to convert buffer to string. Defaults to false.
|
|
87
|
+
* @returns {String|Buffer} The decrypted text
|
|
88
|
+
*/
|
|
89
|
+
function symmetricDecrypt(input, {
|
|
90
|
+
encryptionAlgo = 'aes-256-cbc',
|
|
91
|
+
encryptionKey = undefined,
|
|
92
|
+
outputBuffer = false
|
|
93
|
+
} = {}) {
|
|
94
|
+
let decryptedResult;
|
|
95
|
+
try {
|
|
96
|
+
const textParts = input.split(':');
|
|
97
|
+
const iv = Buffer.from(textParts.shift(), 'hex');
|
|
98
|
+
const encryptedData = Buffer.from(textParts.join(':'), 'hex');
|
|
99
|
+
const key = Buffer.from(encryptionKey ?? process.env.HS_ENCRYPTION_KEY, 'hex');
|
|
100
|
+
const decipher = _nodeCrypto.default.createDecipheriv(encryptionAlgo, key, iv);
|
|
101
|
+
const decrypted = decipher.update(encryptedData);
|
|
102
|
+
const decryptedBuffer = Buffer.concat([decrypted, decipher.final()]);
|
|
103
|
+
decryptedResult = outputBuffer ? decryptedBuffer : decryptedBuffer.toString();
|
|
104
|
+
} catch (e) {
|
|
105
|
+
throw new _errors.HSError(_errors.HSError.HSE_DECRYPT, e);
|
|
106
|
+
}
|
|
107
|
+
return decryptedResult;
|
|
108
|
+
}
|
package/jest.config.js
ADDED
package/lib/errors.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error type for hmac symmetric.
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
5
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export class HSError extends Error {
|
|
9
|
+
static HSE_HMAC = 'HSE_HMAC';
|
|
10
|
+
static HSE_ENCRYPT = 'HSE_ENCRYPT';
|
|
11
|
+
static HSE_DECRYPT = 'HSE_DECRYPT';
|
|
12
|
+
|
|
13
|
+
#hseType;
|
|
14
|
+
get hseType () {
|
|
15
|
+
return this.#hseType;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
constructor (hsErrorType, originalError) {
|
|
19
|
+
super(originalError.message, { cause: originalError });
|
|
20
|
+
this.#hseType = hsErrorType;
|
|
21
|
+
this.name = 'HSError';
|
|
22
|
+
}
|
|
23
|
+
}
|
package/lib/helpers.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Convenience methods for hmac symmetric.
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
5
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
6
|
+
*/
|
|
7
|
+
import { generateHmac, symmetricEncrypt, symmetricDecrypt } from './utils.js';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Generate hmac and symmetrically encrypted payload.
|
|
11
|
+
*
|
|
12
|
+
* @param {String|Buffer|TypedArray|DataView} input - The data to encrypt.
|
|
13
|
+
* @param {Object} [options] - Optional options, @see utils.js
|
|
14
|
+
* @returns {Object} - { digest, payload } on success, throws HSError on error.
|
|
15
|
+
*/
|
|
16
|
+
export function encryptAndDigest (input, options) {
|
|
17
|
+
return {
|
|
18
|
+
digest: generateHmac(input, options),
|
|
19
|
+
payload: symmetricEncrypt(input, options)
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Decrypt encrypted input and check hmac digest with original.
|
|
25
|
+
*
|
|
26
|
+
* @param {String} originalDigest - The original hmac digest to test against.
|
|
27
|
+
* @param {String} encryptedInput - The encrypted input data string.
|
|
28
|
+
* @param {Object} [options] - Optional options, @see utils.js
|
|
29
|
+
* @returns {Object} - { ok, decrypted } on success, throws HSError on error.
|
|
30
|
+
*/
|
|
31
|
+
export function decryptAndTest (originalDigest, encryptedInput, options) {
|
|
32
|
+
const decrypted = symmetricDecrypt(encryptedInput, options);
|
|
33
|
+
const digest = generateHmac(decrypted, options);
|
|
34
|
+
return {
|
|
35
|
+
ok: digest === originalDigest,
|
|
36
|
+
decrypted
|
|
37
|
+
};
|
|
38
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hmac-symmetric exports
|
|
3
|
+
*
|
|
4
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
5
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
6
|
+
*/
|
|
7
|
+
export { generateHmac, symmetricEncrypt, symmetricDecrypt } from './utils.js';
|
|
8
|
+
export { encryptAndDigest, decryptAndTest } from './helpers.js';
|
package/lib/utils.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hmac and symmetric encryption utility methods.
|
|
3
|
+
* sha256 hmac, aes-256-cbc symmetric encryption.
|
|
4
|
+
*
|
|
5
|
+
* Relies on the following environment:
|
|
6
|
+
* process.env.HS_ENCRYPTION_KEY
|
|
7
|
+
* process.env.HS_HMAC_SECRET
|
|
8
|
+
*
|
|
9
|
+
* Copyright (c) 2023 Alex Grant (@localnerve), LocalNerve LLC
|
|
10
|
+
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
|
|
11
|
+
*/
|
|
12
|
+
import crypto from 'node:crypto';
|
|
13
|
+
import { HSError } from './errors.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Generate an HMAC digest using the HMAC secret.
|
|
17
|
+
*
|
|
18
|
+
* @param {String|Buffer|TypedArray|DataView} input - Input data.
|
|
19
|
+
* @param {Object} [options] - Optional options.
|
|
20
|
+
* @param {String} [options.inputEncoding] - Applied if input is String. Default 'utf8'.
|
|
21
|
+
* @param {String} [options.hmacAlgo] - Algo used to create HMAC. Default 'sha256'.
|
|
22
|
+
* @param {String} [options.hmacSecret] - Secret to use. Defaults to environment HS_HMAC_SECRET.
|
|
23
|
+
* @returns {String} Hmac digest as hex string.
|
|
24
|
+
*/
|
|
25
|
+
export function generateHmac (input, {
|
|
26
|
+
inputEncoding = 'utf8',
|
|
27
|
+
hmacAlgo = 'sha256',
|
|
28
|
+
hmacSecret = undefined
|
|
29
|
+
} = {}) {
|
|
30
|
+
let hmacDigest;
|
|
31
|
+
|
|
32
|
+
try {
|
|
33
|
+
const hmac = crypto.createHmac(
|
|
34
|
+
hmacAlgo, hmacSecret ?? process.env.HS_HMAC_SECRET
|
|
35
|
+
);
|
|
36
|
+
hmac.update(input, inputEncoding);
|
|
37
|
+
hmacDigest = hmac.digest('hex').toString();
|
|
38
|
+
} catch (e) {
|
|
39
|
+
throw new HSError(HSError.HSE_HMAC, e);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return hmacDigest;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Symmetrically encrypt the input using the shared encryption key.
|
|
47
|
+
*
|
|
48
|
+
* @param {String|Buffer|TypedArray|DataView} input - The data to encrypt.
|
|
49
|
+
* @param {Object} [options] - Optional options.
|
|
50
|
+
* @param {String} [options.encryptionAlgo] - Symmetric cipher algo, defaults to 'aes-256-cbc'.
|
|
51
|
+
* @param {String} [options.encryptionKey] - Symmetric cipher key. Defaults to environment HS_ENCRYPTION_KEY.
|
|
52
|
+
* @param {String} [options.inputEncoding] - Encoding if the input is a String. Defaults to 'utf8'.
|
|
53
|
+
* @returns {String} Hex encoded encrypted string of the input
|
|
54
|
+
*/
|
|
55
|
+
export function symmetricEncrypt (input, {
|
|
56
|
+
encryptionAlgo = 'aes-256-cbc',
|
|
57
|
+
encryptionKey = undefined,
|
|
58
|
+
inputEncoding = 'utf8'
|
|
59
|
+
} = {}) {
|
|
60
|
+
let encryptionString;
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
const iv = crypto.randomBytes(16);
|
|
64
|
+
const key = Buffer.from(
|
|
65
|
+
encryptionKey ?? process.env.HS_ENCRYPTION_KEY, 'hex'
|
|
66
|
+
);
|
|
67
|
+
const cipher = crypto.createCipheriv(encryptionAlgo, key, iv);
|
|
68
|
+
|
|
69
|
+
let encrypted = cipher.update(input, inputEncoding);
|
|
70
|
+
encrypted = Buffer.concat([encrypted, cipher.final()]);
|
|
71
|
+
encryptionString = `${iv.toString('hex')}:${encrypted.toString('hex')}`;
|
|
72
|
+
} catch (e) {
|
|
73
|
+
throw new HSError(HSError.HSE_ENCRYPT, e);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return encryptionString;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Symmetrically decrypt the ecrypted input using the shared encryption key.
|
|
81
|
+
*
|
|
82
|
+
* @param {String} input - The encrypted data.
|
|
83
|
+
* @param {Object} [options] - Optional options.
|
|
84
|
+
* @param {String} [options.encryptionAlgo] - Symmetric cipher algo, defaults to 'aes-256-cbc'.
|
|
85
|
+
* @param {String} [options.encryptionKey] - Symmetric cipher key. Defaults to environment HS_ENCRYPTION_KEY.
|
|
86
|
+
* @param {Boolean} [options.outputBuffer] - true to return the Buffer result, false to convert buffer to string. Defaults to false.
|
|
87
|
+
* @returns {String|Buffer} The decrypted text
|
|
88
|
+
*/
|
|
89
|
+
export function symmetricDecrypt (input, {
|
|
90
|
+
encryptionAlgo = 'aes-256-cbc',
|
|
91
|
+
encryptionKey = undefined,
|
|
92
|
+
outputBuffer = false
|
|
93
|
+
} = {}) {
|
|
94
|
+
let decryptedResult;
|
|
95
|
+
|
|
96
|
+
try {
|
|
97
|
+
const textParts = input.split(':');
|
|
98
|
+
const iv = Buffer.from(textParts.shift(), 'hex');
|
|
99
|
+
|
|
100
|
+
const encryptedData = Buffer.from(textParts.join(':'), 'hex');
|
|
101
|
+
const key = Buffer.from(
|
|
102
|
+
encryptionKey ?? process.env.HS_ENCRYPTION_KEY, 'hex'
|
|
103
|
+
);
|
|
104
|
+
const decipher = crypto.createDecipheriv(encryptionAlgo, key, iv);
|
|
105
|
+
|
|
106
|
+
const decrypted = decipher.update(encryptedData);
|
|
107
|
+
const decryptedBuffer = Buffer.concat([decrypted, decipher.final()]);
|
|
108
|
+
decryptedResult = outputBuffer ? decryptedBuffer : decryptedBuffer.toString();
|
|
109
|
+
} catch (e) {
|
|
110
|
+
throw new HSError(HSError.HSE_DECRYPT, e);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return decryptedResult;
|
|
114
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@localnerve/hmac-symmetric",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "A library to generate hmac and symmetrically encrypted payloads",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
"require": "./cjs/index.cjs",
|
|
9
|
+
"import": "./lib/index.js",
|
|
10
|
+
"default": "./lib/index.js"
|
|
11
|
+
},
|
|
12
|
+
"directories": {
|
|
13
|
+
"lib": "lib"
|
|
14
|
+
},
|
|
15
|
+
"scripts": {
|
|
16
|
+
"lint": "eslint .",
|
|
17
|
+
"pretranspile": "rimraf ./cjs",
|
|
18
|
+
"transpile": "babel lib -d cjs --out-file-extension .cjs",
|
|
19
|
+
"posttranspile": "node posttranspile.js",
|
|
20
|
+
"test": "cross-env HS_HMAC_SECRET=deadbeef HS_ENCRYPTION_KEY=56c6a9c6fb56a39e05fb993918ab01dda24439e2658dd7b06aa0f8fcc7fe0627 jest && npm run test-package",
|
|
21
|
+
"test-package": "node ./test-package/index.js"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "git+https://github.com/localnerve/hmac-symmetric.git"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"hmac",
|
|
29
|
+
"symmetric",
|
|
30
|
+
"encryption",
|
|
31
|
+
"crypto"
|
|
32
|
+
],
|
|
33
|
+
"author": "Alex Grant <alex@localnerve.com>",
|
|
34
|
+
"maintainers": [
|
|
35
|
+
{
|
|
36
|
+
"name": "localnerve",
|
|
37
|
+
"email": "alex@localnerve.com",
|
|
38
|
+
"url": "https://github.com/localnerve"
|
|
39
|
+
}
|
|
40
|
+
],
|
|
41
|
+
"license": "BSD-3-Clause",
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/localnerve/hmac-symmetric/issues"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/localnerve/hmac-symmetric#readme",
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@babel/cli": "^7.22.10",
|
|
48
|
+
"@babel/preset-env": "^7.22.14",
|
|
49
|
+
"cross-env": "^7.0.3",
|
|
50
|
+
"rimraf": "^5.0.1",
|
|
51
|
+
"jest": "^29.6.4",
|
|
52
|
+
"eslint": "^8.48.0",
|
|
53
|
+
"tar": "^6.1.15",
|
|
54
|
+
"glob": "^10.3.3"
|
|
55
|
+
},
|
|
56
|
+
"engines": {
|
|
57
|
+
"node": ">= 16"
|
|
58
|
+
}
|
|
59
|
+
}
|
package/posttranspile.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
const dir = './cjs';
|
|
5
|
+
const files = await fs.readdir(dir);
|
|
6
|
+
for (const file of files) {
|
|
7
|
+
const filename = `${dir}${path.sep}${file}`;
|
|
8
|
+
const data = await fs.readFile(filename, 'utf8');
|
|
9
|
+
const newData = data.replace(/(require\("[a-z./]+)(\.js"\);)/g, (m, req) => {
|
|
10
|
+
return `${req}.cjs");`;
|
|
11
|
+
});
|
|
12
|
+
await fs.writeFile(filename, newData);
|
|
13
|
+
}
|