ncrypt-js 2.0.1 → 2.1.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/README.md CHANGED
@@ -6,25 +6,17 @@
6
6
 
7
7
  **_NcryptJs_** is a light weight javascript data encryption and decryption library. This library implements the nodejs default crypto functionality as a mid-channel cipher in addition to a simple and elegant custom data encoding and encryption algorithm.
8
8
 
9
- <!-- ```diff
10
- - const ReduxThunk = require('redux-thunk')
11
- + const ReduxThunk = require('redux-thunk').default
12
- ``` -->
13
-
14
9
  ## Contents
15
10
 
16
11
  * [NcryptJs](#NcryptJs)
17
12
  * [Contents](#contents)
18
- <!-- * [Changes Log (What's New)](#changes-log-whats-new) -->
19
13
  * [Getting Started](#getting-started)
20
14
  * [Installation](#installation)
21
15
  * [Documentation](#documentation)
22
- * [NcryptJs Functions](#ncryptjs-functions)
23
- * [Using `encrypt()` and `decrypt()`](#using-encrypt-and-decrypt)
24
- * [Using default imports](#Using-default-imports)
25
- <!-- * [Change the Secret Key](#change-the-secret-key)
26
- * [Object Encryption](#object-encryption)
27
- * [Random Key Generator](#random-key-generator) -->
16
+ * [NcryptJs Methods](#ncryptjs-methods)
17
+ * [Using the `randomString()` methods](#using-randomstring-method)
18
+ * [Using `encrypt()` and `decrypt()` methods](#using-encrypt-and-decrypt-methods)
19
+ * [Using default imports](#using-default-imports)
28
20
  * [Built With](#built-with)
29
21
  * [Contribution](#contribution)
30
22
  * [Version Management](#version-management)
@@ -82,23 +74,38 @@ However, if you are using ECMAScript 5 and older, use the require statement:
82
74
 
83
75
  **_NcryptJs_** is a simple library with only two two exposed functions. This is all intentional mainly to keep everything simple. This is a complete documentation of the library and how to use it in your project. All examples work on both ECMAScript 6 (and later) and ECMAScript 5 (and older).
84
76
 
85
- ### NcryptJs Functions
77
+ ### NcryptJs Methods
86
78
 
87
79
 
88
- ### List of **_NcryptJs_** functions.
80
+ ### List of **_NcryptJs_** Methods.
89
81
 
90
82
 
91
83
 
92
- | Functions | Description | Parameters | Return |
84
+ | Methods | Description | Parameters | Return |
93
85
  | ------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
86
+ | [_static_] **randomString()** | Random String. |**size**: _number_ - An optional size of the generated `randomBytes`. <br/>**enc:** _base64/hex_ - Encoding used for encoding the `randomBytes` defaults to _`base64`_ |**encoded**: _string_ - encoded string. |
94
87
  | **encrypt()** | Encrypts data. |**data**: _object/string/number/boolean_ - The data to be encrypted. <br/>|**ciphered**: _string_ - encrypted data. |
95
88
  | **decrypt()** | Decrypts the encrypted or ciphered data | **encodedData**: string - The encrypted data: _string_ to be decrypted. | **data**: _string/object/number/boolean_ - The decrypted or original data (it might be string or object, depends on the initial input data type).
96
89
 
97
90
 
91
+ ### Using randomString method
92
+
93
+ The `randomString()` static method can generate [random bytes](https://nodejs.org/api/crypto.html#cryptorandombytessize-callback) encoded into a `hexadecimal` or `base64` strings. This string can be useful in a variety of use cases e.g to generate database ids, to generate a unique string for a list, a unique serial strings etc.
94
+
95
+ ```ts
96
+ var ncrypt = require('ncrypt-js');
97
+
98
+ var randomStr = ncrypt.randomString(8, 'base64');
99
+ console.log(randomStr) // t78WcmYAFOY=
98
100
 
99
- #### Using `encrypt()` and `decrypt()` functons - As of version 2.0.0 directly importing or invoking these functions is deprecated, an object must be created with a secret first, before the methods can now be invoked on the created object.
101
+ // signature
102
+ ncrypt.randomString(size?: number, enc?: 'base64' | 'hex');
103
+ ```
100
104
 
101
- To encrypt and decrypt data, simply use `encrypt()` and `decrypt()` functions respectively. This will use `AES-256-CBC` encryption algorithm as the mid-channel cipher.
105
+ ### Using encrypt() and decrypt() methods
106
+ The `encrypt()` and `decrypt()` methods as of version 2.0.0 directly importing or invoking these methods is deprecated, an object must be created with a secret first, before the methods can now be invoked on the created object.
107
+
108
+ To `encrypt` and `decrypt` data, simply use `encrypt()` and `decrypt()` methods respectively. This will use `AES-256-CBC` encryption algorithm as the mid-channel cipher.
102
109
 
103
110
  ```diff
104
111
  - var { encrypt, decrypt } = require("ncrypt-js");
@@ -108,7 +115,7 @@ To encrypt and decrypt data, simply use `encrypt()` and `decrypt()` functions re
108
115
  var data = "Hello World!";
109
116
  var _secretKey = "some-super-secret-key";
110
117
 
111
- + var { encodeData, decodeData } = new ncrypt(_secretKey);
118
+ + var { encrypt, decrypt } = new ncrypt(_secretKey);
112
119
 
113
120
  // encrypting super sensitive data here
114
121
  - var encryptedData = encrypt(data, _secretKey);
@@ -180,11 +187,16 @@ console.log("...done.");
180
187
  ````
181
188
  If you are using any sort of environmental key-value store, e.g `.env` and for additional security, you can add the following to your environment.
182
189
 
183
- ```diff
184
- // .env
190
+ ```bash
191
+ # .env
192
+
193
+ # used internally to set the `key`
194
+ KEY='sshhhh this is a super secret key'
195
+
196
+ # used internally to set the `encoding` - ['base64' | 'binary' | 'hex' | 'ucs-2' | 'ucs2' | 'utf16le']
197
+ NCRPT_ENC='hex'
185
198
 
186
- KEY=sshhhh this is a super secret key
187
- SECRET=this is our hashing secret
199
+ SECRET='this is our hashing secret'
188
200
  ```
189
201
  Then when creating your object, you can use the SECRET from your environment e.g:
190
202
  ```
@@ -0,0 +1,3 @@
1
+ import ncrypt from './src/ncrypt';
2
+ export default ncrypt;
3
+ export { ncrypt };
package/dist/index.js CHANGED
@@ -3,7 +3,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ncrypt = void 0;
7
6
  const ncrypt_1 = __importDefault(require("./src/ncrypt"));
8
7
  exports.ncrypt = ncrypt_1.default;
9
8
  module.exports = ncrypt_1.default;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @class Ncrypt
3
+ * @type {Ncrypt.<object>}
4
+ */
5
+ export default class Ncrypt {
6
+ /**
7
+ * encryption secret.
8
+ * @type {secret.<string>} secret
9
+ */
10
+ private secret;
11
+ /**
12
+ * algorithm used for encoding message
13
+ */
14
+ private readonly algorithm;
15
+ /**
16
+ * ecoding for encrypted stirng
17
+ */
18
+ private readonly enc;
19
+ /**
20
+ * crypto random initial vector generated from core node {crypto} module
21
+ */
22
+ private readonly initialVector;
23
+ /**
24
+ * crypto random key generated from core node {crypto} module
25
+ * {note}: please read the value for KEY from your app's environment
26
+ */
27
+ private readonly key;
28
+ /**
29
+ * object constructor
30
+ * @param {secret.<string>} secret
31
+ */
32
+ constructor(secret: string);
33
+ /**
34
+ * convert all entered text to decimal equivalent character codes
35
+ * @param {text.<string>} text to be converted
36
+ * @return {Array.<number>} array of character codes
37
+ */
38
+ private convertTextToDecimal;
39
+ /**
40
+ * encode provided secret on decimal character codes
41
+ * @param {charCode.<number, number[]>} charCodes
42
+ * @returns {*.<number>} decimal string
43
+ */
44
+ private applySecretToCharacters;
45
+ /**
46
+ * convert character bytes to hexadecimal equivalent
47
+ * @param {number.<number>} number
48
+ * @returns {*.<string>} hexadecimal string
49
+ */
50
+ private convertByteToHexadecimal;
51
+ /**
52
+ * intermediate data encoder function
53
+ * @param {string.<any>} text
54
+ * @param secret
55
+ * @returns {string} encrypted or cipher text
56
+ */
57
+ private encode;
58
+ /**
59
+ * intermediate data decoder function
60
+ * @param {string.<any>} text
61
+ * @returns {string.<string>} decrypted data
62
+ */
63
+ private decode;
64
+ /**
65
+ * generate random strings
66
+ * @example
67
+ *
68
+ * var fs = require('fs');
69
+ * var ncrypt = require('ncrypt-js');
70
+ *
71
+ * console.log(ncrypt.randomString(8, 'base64')); // g3lzZ48TW6w==
72
+ *
73
+ * @param {size.<number>} size
74
+ * @param {enc.<string>} enc
75
+ * @returns {*.<string>} string
76
+ */
77
+ static randomString(size?: number, enc?: 'hex' | 'base64'): string;
78
+ /**
79
+ * data to be encrypted
80
+ * @param {data.<stirng>} data
81
+ * @returns {*.<string>} encrypted text
82
+ */
83
+ encrypt(data: string | number | boolean | object): string;
84
+ /**
85
+ * text be decrypted
86
+ * @param {text.<stirng>} text
87
+ * @returns {*.<string>} decrypted data
88
+ */
89
+ decrypt(text: string): string | number | boolean | object;
90
+ }
@@ -1,75 +1,152 @@
1
1
  "use strict";
2
+ var __importStar = (this && this.__importStar) || function (mod) {
3
+ if (mod && mod.__esModule) return mod;
4
+ var result = {};
5
+ if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
6
+ result["default"] = mod;
7
+ return result;
8
+ };
2
9
  Object.defineProperty(exports, "__esModule", { value: true });
3
- const utils_1 = require("./utils");
10
+ const crypto = __importStar(require("crypto"));
11
+ /**
12
+ * @class Ncrypt
13
+ * @type {Ncrypt.<object>}
14
+ */
4
15
  class Ncrypt {
5
16
  /**
6
17
  * object constructor
7
- * @param text
8
- * @param secret
18
+ * @param {secret.<string>} secret
9
19
  */
10
20
  constructor(secret) {
21
+ /**
22
+ * algorithm used for encoding message
23
+ */
24
+ this.algorithm = 'aes-256-cbc';
25
+ /**
26
+ * ecoding for encrypted stirng
27
+ */
28
+ this.enc = (process.env.NCRYPT_ENC) || 'hex';
29
+ /**
30
+ * crypto random initial vector generated from core node {crypto} module
31
+ */
32
+ this.initialVector = crypto.randomBytes(16);
33
+ /**
34
+ * crypto random key generated from core node {crypto} module
35
+ * {note}: please read the value for KEY from your app's environment
36
+ */
37
+ this.key = crypto.scryptSync(process.env.KEY || 'please provide a KEY in your .env file or config', 'salt', 32);
11
38
  /**
12
39
  * convert all entered text to decimal equivalent character codes
13
- * @param {data.<string>} data to be converted
40
+ * @param {text.<string>} text to be converted
14
41
  * @return {Array.<number>} array of character codes
15
42
  */
16
- this.convertTextToDecimal = (data) => data.split('').map((value) => value.charCodeAt(0));
43
+ this.convertTextToDecimal = (text) => {
44
+ return text.split('').map((value) => value.charCodeAt(0));
45
+ };
17
46
  /**
18
47
  * encode provided secret on decimal character codes
19
- * @param {charCode<number[], *>} character codes
48
+ * @param {charCode.<number, number[]>} charCodes
49
+ * @returns {*.<number>} decimal string
20
50
  */
21
- this.applySecretToCharacters = (charCodes) => this.convertTextToDecimal(this.secret)
22
- .reduce((firstValue, secondValue) => (firstValue ^ secondValue), charCodes);
51
+ this.applySecretToCharacters = (charCodes) => {
52
+ return this.convertTextToDecimal(this.secret)
53
+ .reduce((firstValue, secondValue) => (firstValue ^ secondValue), charCodes);
54
+ };
23
55
  /**
24
56
  * convert character bytes to hexadecimal equivalent
25
- * @param {number.<number>}
26
- * @returns {string} hexadecimal string
57
+ * @param {number.<number>} number
58
+ * @returns {*.<string>} hexadecimal string
27
59
  */
28
60
  this.convertByteToHexadecimal = (number) => {
29
- return ("0" + Number(number).toString(16)).substr(-2);
61
+ return ('0' + Number(number).toString(16)).substr(-2);
30
62
  };
31
63
  /**
32
- * process data to be encrypted
33
- * @param {}
34
- * @returns {string.<string>} encoded string data
64
+ * intermediate data encoder function
65
+ * @param {string.<any>} text
66
+ * @param secret
67
+ * @returns {string} encrypted or cipher text
35
68
  */
36
- this.encrypt = (data) => {
37
- /**
38
- * this does the actual processing return a string
39
- * resulting from charCode conversion, salting and
40
- * hexadecimal mapping
41
- *
42
- */
43
- // if (data == void 0) throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
44
- try {
45
- const encodedMessage = JSON.stringify(data).split('')
46
- .map(this.convertTextToDecimal)
47
- .map(this.applySecretToCharacters)
48
- .map(this.convertByteToHexadecimal)
49
- .join('');
50
- return utils_1.encode(encodedMessage);
51
- }
52
- catch (error) {
53
- throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
69
+ this.encode = (text) => {
70
+ let cipher = crypto.createCipheriv(this.algorithm, Buffer.from(this.key), this.initialVector);
71
+ let encrypted = cipher.update(text);
72
+ encrypted = Buffer.concat([encrypted, cipher.final()]);
73
+ return `${this.initialVector.toString(this.enc)}.${encrypted.toString(this.enc)}`;
74
+ };
75
+ /**
76
+ * intermediate data decoder function
77
+ * @param {string.<any>} text
78
+ * @returns {string.<string>} decrypted data
79
+ */
80
+ this.decode = (text) => {
81
+ if (typeof text !== 'string') {
82
+ throw new TypeError('argument must be a string, or a string-like object');
54
83
  }
84
+ const iv = text.split('.')[0];
85
+ const encryptedData = text.split('.')[1];
86
+ let _iv = Buffer.from(iv, this.enc);
87
+ let encryptedText = Buffer.from(encryptedData, this.enc);
88
+ let decipher = crypto.createDecipheriv(this.algorithm, Buffer.from(this.key), _iv);
89
+ let decrypted = decipher.update(encryptedText);
90
+ decrypted = Buffer.concat([decrypted, decipher.final()]);
91
+ return decrypted.toString();
55
92
  };
93
+ this.secret = secret;
94
+ // bind public instnace methods
95
+ this.encrypt = this.encrypt.bind(this);
96
+ this.decrypt = this.decrypt.bind(this);
97
+ }
98
+ /**
99
+ * generate random strings
100
+ * @example
101
+ *
102
+ * var fs = require('fs');
103
+ * var ncrypt = require('ncrypt-js');
104
+ *
105
+ * console.log(ncrypt.randomString(8, 'base64')); // g3lzZ48TW6w==
106
+ *
107
+ * @param {size.<number>} size
108
+ * @param {enc.<string>} enc
109
+ * @returns {*.<string>} string
110
+ */
111
+ static randomString(size, enc = 'base64') {
112
+ return crypto.randomBytes(size || 64).toString(enc);
113
+ }
114
+ /**
115
+ * data to be encrypted
116
+ * @param {data.<stirng>} data
117
+ * @returns {*.<string>} encrypted text
118
+ */
119
+ encrypt(data) {
56
120
  /**
57
- * decodes encoded string resulting from util encryption
58
- * @param {string.<stirng>} encodeData
59
- * @returns {decodedData.<string>} decoded data
121
+ * this does the actual processing return a string
122
+ * resulting from charCode conversion, salting and
123
+ * hexadecimal mapping
60
124
  */
61
- this.decrypt = (text) => {
62
- const encodeData = utils_1.decode(text);
63
- const data = encodeData.match(/.{1,2}/g)
64
- .map((hex) => parseInt(hex, 16))
125
+ try {
126
+ const encodedMessage = JSON.stringify(data).split('')
127
+ .map(this.convertTextToDecimal)
65
128
  .map(this.applySecretToCharacters)
66
- .map((charCode) => String.fromCharCode(charCode))
129
+ .map(this.convertByteToHexadecimal)
67
130
  .join('');
68
- const arr = [];
69
- arr.push(data);
70
- return JSON.parse(data);
71
- };
72
- this.secret = secret;
131
+ return this.encode(encodedMessage);
132
+ }
133
+ catch (e) {
134
+ throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.' + e);
135
+ }
136
+ }
137
+ /**
138
+ * text be decrypted
139
+ * @param {text.<stirng>} text
140
+ * @returns {*.<string>} decrypted data
141
+ */
142
+ decrypt(text) {
143
+ const encodeData = this.decode(text);
144
+ const data = (encodeData).match(/.{1,2}/g)
145
+ .map((hex) => parseInt(hex, 16))
146
+ .map(this.applySecretToCharacters)
147
+ .map((charCode) => String.fromCharCode(charCode))
148
+ .join('');
149
+ return JSON.parse(data);
73
150
  }
74
151
  }
75
152
  exports.default = Ncrypt;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ncrypt-js",
3
- "version": "2.0.1",
3
+ "version": "2.1.0",
4
4
  "description": "a light weight javascript data encryption and decryption library",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -28,7 +28,7 @@
28
28
  "decryption",
29
29
  "javascript-library"
30
30
  ],
31
- "author": "meeky",
31
+ "author": "ajimae",
32
32
  "license": "MIT",
33
33
  "bugs": {
34
34
  "url": "https://github.com/ajimae/ncrypt-js/issues"
@@ -46,7 +46,7 @@
46
46
  "mocha-lcov-reporter": "^1.3.0",
47
47
  "nyc": "^14.1.1",
48
48
  "ts-node": "^8.6.2",
49
- "typescript": "^3.8.3"
49
+ "typescript": "3.8.3"
50
50
  },
51
51
  "files": [
52
52
  "dist",
@@ -55,7 +55,6 @@
55
55
  "tsconfig.json"
56
56
  ],
57
57
  "dependencies": {
58
- "crypto": "^1.0.1",
59
- "dotenv": "^16.4.5"
58
+ "crypto": "^1.0.1"
60
59
  }
61
60
  }
package/tsconfig.json CHANGED
@@ -6,6 +6,7 @@
6
6
  "esModuleInterop": true,
7
7
  "noImplicitAny": true,
8
8
  "moduleResolution": "node",
9
+ "declaration": true,
9
10
  "sourceMap": false,
10
11
  "outDir": "dist",
11
12
  "baseUrl": ".",
package/dist/src/utils.js DELETED
@@ -1,49 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.decode = exports.encode = void 0;
7
- const crypto_1 = __importDefault(require("crypto")); // this is necessary for some version of nodejs without crypto module
8
- const algorithm = 'aes-256-cbc';
9
- /**
10
- * crypto random initial vector generated from core node {crypto} module
11
- */
12
- const initialVector = crypto_1.default.randomBytes(16);
13
- /**
14
- * crypto random key generated from core node {crypto} module
15
- *
16
- * {note}: please read the value for KEY from your app's environment
17
- */
18
- const _key = process.env.KEY || 'please provide a KEY in your .env file or config';
19
- const key = crypto_1.default.scryptSync(_key, 'salt', 32);
20
- /**
21
- * intermediate data encoder function
22
- * @param {string.<any>} text
23
- * @param secret
24
- * @returns {string} encrypted or cipher text
25
- */
26
- exports.encode = (text) => {
27
- let cipher = crypto_1.default.createCipheriv(algorithm, Buffer.from(key), initialVector);
28
- let encrypted = cipher.update(text);
29
- encrypted = Buffer.concat([encrypted, cipher.final()]);
30
- return `${initialVector.toString('hex')}.${encrypted.toString('hex')}`;
31
- };
32
- /**
33
- * intermediate data decoder function
34
- * @param {string.<any>} text
35
- * @returns {string.<string>} decrypted data
36
- */
37
- exports.decode = (text) => {
38
- if (typeof text !== 'string') {
39
- throw new TypeError('argument must be a string, or a string-like object');
40
- }
41
- const iv = text.split('.')[0];
42
- const encryptedData = text.split('.')[1];
43
- let _iv = Buffer.from(iv, 'hex');
44
- let encryptedText = Buffer.from(encryptedData, 'hex');
45
- let decipher = crypto_1.default.createDecipheriv(algorithm, Buffer.from(key), _iv);
46
- let decrypted = decipher.update(encryptedText);
47
- decrypted = Buffer.concat([decrypted, decipher.final()]);
48
- return decrypted.toString();
49
- };