ncrypt-js 2.0.0 → 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
@@ -1,30 +1,22 @@
1
1
  # NcryptJs
2
2
 
3
- [![Build Status](https://travis-ci.com/ajimae/ncrypt-js.svg?branch=master)](https://travis-ci.com/ajimae/ncrypt-js) [![Coverage Status](https://coveralls.io/repos/github/ajimae/ncrypt-js/badge.svg)](https://coveralls.io/github/ajimae/ncrypt-js) ![NPM](https://img.shields.io/npm/l/ncrypt-js)
3
+ [![Build Status](https://travis-ci.com/ajimae/ncrypt-js.svg?branch=master)](https://travis-ci.com/ajimae/ncrypt-js) [![Coverage Status](https://coveralls.io/repos/github/ajimae/ncrypt-js/badge.svg)](https://coveralls.io/github/ajimae/ncrypt-js) [![NPM](https://img.shields.io/npm/l/ncrypt-js)](https://www.npmjs.com/package/ncrypt-js/v/2.0.0#license)
4
4
 
5
- ![GitHub release (latest by date)](https://img.shields.io/github/v/release/ajimae/ncrypt-js) ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/ajimae/ncrypt-js) ![GitHub issues](https://img.shields.io/github/issues/ajimae/ncrypt-js)
5
+ [![GitHub release (latest by date)](https://img.shields.io/github/v/release/ajimae/ncrypt-js)](https://github.com/ajimae/ncrypt-js/releases) [![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/ajimae/ncrypt-js)](https://github/languages/code-size/ajimae/ncrypt-js) [![GitHub issues](https://img.shields.io/github/issues/ajimae/ncrypt-js)](https://github.com/ajimae/ncrypt-js/issues)
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.
98
94
 
99
- ### Using `encrypt()` and `decrypt()` functons - As of version 1.1.0 this is deprecated, an object must be created first.
95
+ ```ts
96
+ var ncrypt = require('ncrypt-js');
100
97
 
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.
98
+ var randomStr = ncrypt.randomString(8, 'base64');
99
+ console.log(randomStr) // t78WcmYAFOY=
100
+
101
+ // signature
102
+ ncrypt.randomString(size?: number, enc?: 'base64' | 'hex');
103
+ ```
104
+
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);
@@ -177,6 +184,26 @@ var decryptedObject = ncryptObject.decrypt(encryptedObject);
177
184
  console.log("... and then decryption...");
178
185
  console.log("Decipher Text : " + decryptedObject);
179
186
  console.log("...done.");
187
+ ````
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.
189
+
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'
198
+
199
+ SECRET='this is our hashing secret'
200
+ ```
201
+ Then when creating your object, you can use the SECRET from your environment e.g:
202
+ ```
203
+ ...
204
+ var ncrypt = require('ncrypt-js');
205
+ var { encrypt, decrypt } = new ncrypt(process.env.SECRET);
206
+ ...
180
207
  ```
181
208
 
182
209
  ## Built With
@@ -1,7 +1,3 @@
1
1
  import ncrypt from './src/ncrypt';
2
-
3
- module.exports = ncrypt;
4
2
  export default ncrypt;
5
- export {
6
- ncrypt
7
- }
3
+ export { ncrypt };
package/dist/index.js CHANGED
@@ -7,4 +7,3 @@ const ncrypt_1 = __importDefault(require("./src/ncrypt"));
7
7
  exports.ncrypt = ncrypt_1.default;
8
8
  module.exports = ncrypt_1.default;
9
9
  exports.default = ncrypt_1.default;
10
- //# sourceMappingURL=index.js.map
@@ -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,76 +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;
76
- //# sourceMappingURL=ncrypt.js.map
package/package.json CHANGED
@@ -1,14 +1,12 @@
1
1
  {
2
2
  "name": "ncrypt-js",
3
- "version": "2.0.0",
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": {
7
- "start": "npm run build && node dist/index",
8
- "start:dev": "ts-node index.ts",
9
7
  "clean": "rm -rf dist",
10
- "prepare": "npm run build",
11
- "build": "tsc --outDir dist",
8
+ "prepare": "yarn build",
9
+ "build": "yarn clean;tsc --outDir dist",
12
10
  "test": "cross-env TS_NODE_FILES=true nyc mocha --exit --require ts-node/register --colors test/**/*.ts",
13
11
  "coverage": "nyc report --reporter=text-lcov | coveralls"
14
12
  },
@@ -30,7 +28,7 @@
30
28
  "decryption",
31
29
  "javascript-library"
32
30
  ],
33
- "author": "meeky",
31
+ "author": "ajimae",
34
32
  "license": "MIT",
35
33
  "bugs": {
36
34
  "url": "https://github.com/ajimae/ncrypt-js/issues"
@@ -48,12 +46,15 @@
48
46
  "mocha-lcov-reporter": "^1.3.0",
49
47
  "nyc": "^14.1.1",
50
48
  "ts-node": "^8.6.2",
51
- "typescript": "^3.8.3"
49
+ "typescript": "3.8.3"
52
50
  },
51
+ "files": [
52
+ "dist",
53
+ "package.json",
54
+ "LICENSE",
55
+ "tsconfig.json"
56
+ ],
53
57
  "dependencies": {
54
- "crypto": "^1.0.1",
55
- "dotenv": "^8.2.0",
56
- "handlebars": "^4.7.3",
57
- "simple-crypto-js": "^2.2.0"
58
+ "crypto": "^1.0.1"
58
59
  }
59
60
  }
package/tsconfig.json CHANGED
@@ -6,7 +6,8 @@
6
6
  "esModuleInterop": true,
7
7
  "noImplicitAny": true,
8
8
  "moduleResolution": "node",
9
- "sourceMap": true,
9
+ "declaration": true,
10
+ "sourceMap": false,
10
11
  "outDir": "dist",
11
12
  "baseUrl": ".",
12
13
  "paths": {
package/.nycrc DELETED
@@ -1,29 +0,0 @@
1
- {
2
- "cache": false,
3
- "check-coverage": false,
4
- "extension": [
5
- ".ts"
6
- ],
7
- "require": [
8
- "ts-node/register"
9
- ],
10
- "include": [
11
- "**/*js",
12
- "**/*ts"
13
- ],
14
- "exclude": [
15
- "dist/**",
16
- "coverage/**",
17
- "node_modules/**",
18
- "**/*.d.ts",
19
- "**/*.test.ts"
20
- ],
21
- "sourceMap": true,
22
- "reporter": [
23
- "html",
24
- "text",
25
- "text-summary"
26
- ],
27
- "all": true,
28
- "instrument": true
29
- }
package/.travis.yml DELETED
@@ -1,11 +0,0 @@
1
- language: node_js
2
- node_js:
3
- - "node"
4
- cache:
5
- directories:
6
- - "node_modules"
7
- script:
8
- - npm test
9
- after_success:
10
- - npm run coverage
11
- - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;;;;AAAA,0DAAkC;AAKhC,iBALK,gBAAM,CAKL;AAHR,MAAM,CAAC,OAAO,GAAG,gBAAM,CAAC;AACxB,kBAAe,gBAAM,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"ncrypt.js","sourceRoot":"","sources":["../../src/ncrypt.ts"],"names":[],"mappings":";;AACA,mCAAyC;AAEzC,MAAqB,MAAM;IAazB;;;;OAIG;IACH,YAAY,MAAc;QAI1B;;;;WAIG;QACH,yBAAoB,GAAG,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;QAE5F;;;WAGG;QACH,4BAAuB,GAAG,CAAC,SAAqC,EAAE,EAAE,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,MAAM,CAAC;aACxG,MAAM,CAAC,CAAC,UAAe,EAAE,WAAgB,EAAE,EAAE,CAAC,CAAC,UAAU,GAAG,WAAW,CAAC,EAAE,SAAS,CAAC,CAAA;QAEvF;;;;WAIG;QACH,6BAAwB,GAAG,CAAC,MAAc,EAAE,EAAE;YAC5C,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;QACxD,CAAC,CAAA;QAED;;;;WAIG;QACH,YAAO,GAAG,CAAC,IAAwC,EAAE,EAAE;YACrD;;;;;eAKG;YACH,0IAA0I;YAC1I,IAAI;gBACF,MAAM,cAAc,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,EAAE,CAAC;qBAClD,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC;qBAC9B,GAAG,CAAC,IAAI,CAAC,uBAAuB,CAAC;qBACjC,GAAG,CAAC,IAAI,CAAC,wBAAwB,CAAC;qBAClC,IAAI,CAAC,EAAE,CAAC,CAAC;gBAEZ,OAAO,cAAM,CAAC,cAAc,CAAC,CAAC;aAC/B;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,iGAAiG,CAAC,CAAC;aACpH;QACH,CAAC,CAAA;QAED;;;;WAIG;QACH,YAAO,GAAG,CAAC,IAAY,EAAE,EAAE;YACzB,MAAM,UAAU,GAAG,cAAM,CAAC,IAAI,CAAC,CAAC;YAE9B,MAAM,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,SAAS,CAAC;iBACrC,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;iBACpC,GAAG,CAAC,IAAI,CAAC,uBAAuB,CAAC;iBACjC,GAAG,CAAC,CAAC,QAAa,EAAE,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC;iBACrD,IAAI,CAAC,EAAE,CAAC,CAAC;YAEV,MAAM,GAAG,GAAG,EAAE,CAAC;YACf,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAEjB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC5B,CAAC,CAAA;QAtEC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CAsEF;AA1FD,yBA0FC"}
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
- const crypto_1 = __importDefault(require("crypto")); // this is necessary for some version of nodejs without crypto module
7
- const algorithm = 'aes-256-cbc';
8
- /**
9
- * crypto random initial vector generated from core node {crypto} module
10
- */
11
- const initialVector = crypto_1.default.randomBytes(16);
12
- /**
13
- * crypto random key generated from core node {crypto} module
14
- *
15
- * {note}: please read the value for KEY from your app's environment
16
- */
17
- const _key = process.env.KEY || 'please provide a KEY in your .env file or config';
18
- const key = crypto_1.default.scryptSync(_key, 'salt', 32);
19
- /**
20
- * intermediate data encoder function
21
- * @param {string.<any>} text
22
- * @param secret
23
- * @returns {string} encrypted or cipher text
24
- */
25
- exports.encode = (text) => {
26
- let cipher = crypto_1.default.createCipheriv(algorithm, Buffer.from(key), initialVector);
27
- let encrypted = cipher.update(text);
28
- encrypted = Buffer.concat([encrypted, cipher.final()]);
29
- return `${initialVector.toString('hex')}.${encrypted.toString('hex')}`;
30
- };
31
- /**
32
- * intermediate data decoder function
33
- * @param {string.<any>} text
34
- * @returns {string.<string>} decrypted data
35
- */
36
- exports.decode = (text) => {
37
- if (typeof text !== 'string') {
38
- throw new TypeError('argument must be a string, or a string-like object');
39
- }
40
- const iv = text.split('.')[0];
41
- const encryptedData = text.split('.')[1];
42
- let _iv = Buffer.from(iv, 'hex');
43
- let encryptedText = Buffer.from(encryptedData, 'hex');
44
- let decipher = crypto_1.default.createDecipheriv(algorithm, Buffer.from(key), _iv);
45
- let decrypted = decipher.update(encryptedText);
46
- decrypted = Buffer.concat([decrypted, decipher.final()]);
47
- return decrypted.toString();
48
- };
49
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B,CAAI,qEAAqE;AAErG,MAAM,SAAS,GAAG,aAAa,CAAC;AAEhC;;GAEG;AACH,MAAM,aAAa,GAAW,gBAAM,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;AAErD;;;;GAIG;AACH,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,kDAAkD,CAAC;AACnF,MAAM,GAAG,GAAW,gBAAM,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;AAExD;;;;;GAKG;AACU,QAAA,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE;IACrC,IAAI,MAAM,GAAG,gBAAM,CAAC,cAAc,CAAC,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,aAAa,CAAC,CAAC;IAC/E,IAAI,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAEpC,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACvD,OAAO,GAAG,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;AACzE,CAAC,CAAA;AAED;;;;GAIG;AACU,QAAA,MAAM,GAAG,CAAC,IAAY,EAAE,EAAE;IAErC,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE;QAC5B,MAAM,IAAI,SAAS,CAAC,oDAAoD,CAAC,CAAC;KAC3E;IAED,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IAEzC,IAAI,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IACjC,IAAI,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;IACtD,IAAI,QAAQ,GAAG,gBAAM,CAAC,gBAAgB,CAAC,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;IACzE,IAAI,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAE/C,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACzD,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC,CAAA"}
package/src/ncrypt.d.ts DELETED
@@ -1,8 +0,0 @@
1
-
2
- export interface INcrypt {
3
- convertTextToDecimal(text: string): number[];
4
- applySecretToCharacters(charCodes: number[] | number): number;
5
- convertByteToHexadecimal(number: number): string;
6
- encrypt(text: object | string | number | boolean): string;
7
- decrypt(data: string): string;
8
- }
package/src/ncrypt.ts DELETED
@@ -1,94 +0,0 @@
1
- import { INcrypt } from './ncrypt.d';
2
- import { encode, decode } from './utils';
3
-
4
- export default class Ncrypt implements INcrypt {
5
-
6
- /**
7
- * ncrypt namespace.
8
- * @type {string.<*>}
9
- */
10
- private secret: string;
11
-
12
- /**
13
- * ncrypt namespace.
14
- * @type {string.<*>}
15
- */
16
- private text: string;
17
- /**
18
- * object constructor
19
- * @param text
20
- * @param secret
21
- */
22
- constructor(secret: string) {
23
- this.secret = secret;
24
- }
25
-
26
- /**
27
- * convert all entered text to decimal equivalent character codes
28
- * @param {data.<string>} data to be converted
29
- * @return {Array.<number>} array of character codes
30
- */
31
- convertTextToDecimal = (data: string) => data.split('').map((value) => value.charCodeAt(0));
32
-
33
- /**
34
- * encode provided secret on decimal character codes
35
- * @param {charCode<number[], *>} character codes
36
- */
37
- applySecretToCharacters = (charCodes: number[] | number | string) => this.convertTextToDecimal(this.secret)
38
- .reduce((firstValue: any, secondValue: any) => (firstValue ^ secondValue), charCodes)
39
-
40
- /**
41
- * convert character bytes to hexadecimal equivalent
42
- * @param {number.<number>}
43
- * @returns {string} hexadecimal string
44
- */
45
- convertByteToHexadecimal = (number: number) => {
46
- return ("0" + Number(number).toString(16)).substr(-2);
47
- }
48
-
49
- /**
50
- * process data to be encrypted
51
- * @param {}
52
- * @returns {string.<string>} encoded string data
53
- */
54
- encrypt = (data: object | string | number | boolean) => {
55
- /**
56
- * this does the actual processing return a string
57
- * resulting from charCode conversion, salting and
58
- * hexadecimal mapping
59
- *
60
- */
61
- // if (data == void 0) throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
62
- try {
63
- const encodedMessage = JSON.stringify(data).split('')
64
- .map(this.convertTextToDecimal)
65
- .map(this.applySecretToCharacters)
66
- .map(this.convertByteToHexadecimal)
67
- .join('');
68
-
69
- return encode(encodedMessage);
70
- } catch (error) {
71
- throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
72
- }
73
- }
74
-
75
- /**
76
- * decodes encoded string resulting from util encryption
77
- * @param {string.<stirng>} encodeData
78
- * @returns {decodedData.<string>} decoded data
79
- */
80
- decrypt = (text: string) => {
81
- const encodeData = decode(text);
82
-
83
- const data = encodeData.match(/.{1,2}/g)
84
- .map((hex: any) => parseInt(hex, 16))
85
- .map(this.applySecretToCharacters)
86
- .map((charCode: any) => String.fromCharCode(charCode))
87
- .join('');
88
-
89
- const arr = [];
90
- arr.push(data);
91
-
92
- return JSON.parse(data);
93
- }
94
- }
package/src/utils.ts DELETED
@@ -1,53 +0,0 @@
1
- import crypto from 'crypto'; // this is necessary for some version of nodejs without crypto module
2
-
3
- const algorithm = 'aes-256-cbc';
4
-
5
- /**
6
- * crypto random initial vector generated from core node {crypto} module
7
- */
8
- const initialVector: Buffer = crypto.randomBytes(16);
9
-
10
- /**
11
- * crypto random key generated from core node {crypto} module
12
- *
13
- * {note}: please read the value for KEY from your app's environment
14
- */
15
- const _key = process.env.KEY || 'please provide a KEY in your .env file or config';
16
- const key: Buffer = crypto.scryptSync(_key, 'salt', 32);
17
-
18
- /**
19
- * intermediate data encoder function
20
- * @param {string.<any>} text
21
- * @param secret
22
- * @returns {string} encrypted or cipher text
23
- */
24
- export const encode = (text: string) => {
25
- let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), initialVector);
26
- let encrypted = cipher.update(text);
27
-
28
- encrypted = Buffer.concat([encrypted, cipher.final()]);
29
- return `${initialVector.toString('hex')}.${encrypted.toString('hex')}`;
30
- }
31
-
32
- /**
33
- * intermediate data decoder function
34
- * @param {string.<any>} text
35
- * @returns {string.<string>} decrypted data
36
- */
37
- export const decode = (text: string) => {
38
-
39
- if (typeof text !== 'string') {
40
- throw new TypeError('argument must be a string, or a string-like object');
41
- }
42
-
43
- const iv = text.split('.')[0];
44
- const encryptedData = text.split('.')[1];
45
-
46
- let _iv = Buffer.from(iv, 'hex');
47
- let encryptedText = Buffer.from(encryptedData, 'hex');
48
- let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), _iv);
49
- let decrypted = decipher.update(encryptedText);
50
-
51
- decrypted = Buffer.concat([decrypted, decipher.final()]);
52
- return decrypted.toString();
53
- }
@@ -1,135 +0,0 @@
1
- import * as chai from "chai";
2
-
3
- import ncrypt from '../index';
4
-
5
- const expect = chai.expect;
6
-
7
- const object = {
8
- NcryptJs: "is great.",
9
- You: "should try it!"
10
- };
11
- const string: string = "ncrypt-js is great.";
12
- const number: number = 19960404;
13
- const boolean: boolean = false;
14
- const _nullData: any = null;
15
-
16
- const _secret = 'shhh its a secret';
17
-
18
- const { encrypt, decrypt } = new ncrypt(_secret);
19
-
20
- const encryptString = encrypt(string);
21
- const encryptNumber = encrypt(number);
22
- const encryptObject = encrypt(object);
23
- const encryptBoolean = encrypt(boolean);
24
- const encryptNullData = encrypt(_nullData);
25
-
26
- const decryptString = decrypt(encryptString);
27
- const decryptNumber = decrypt(encryptNumber);
28
- const decryptObject = decrypt(encryptObject);
29
- const decryptBoolean = decrypt(encryptBoolean);
30
- const decryptNullData = encrypt(_nullData);
31
-
32
- describe('Encrytion', () => {
33
- it('should be able to encrypt a string', () => {
34
- expect(string).to.be.a('string');
35
- expect(typeof encryptString).to.eql('string');
36
- });
37
-
38
- it('should be able to encrypt an object', () => {
39
- expect(object).to.be.a('object');
40
- expect(typeof encryptObject).to.eql('string');
41
- });
42
-
43
- it('should be able to encrypt a number', () => {
44
- expect(number).to.be.a('number');
45
- expect(typeof encryptNumber).to.eql('string');
46
- });
47
-
48
- it('should be able to encrypt a boolean', () => {
49
- expect(boolean).to.be.a('boolean');
50
- expect(typeof encryptBoolean).to.eql('string');
51
- });
52
- });
53
-
54
- describe('Decrytion', () => {
55
- it('should be able to decrypt original string', () => {
56
- expect(decryptString).to.be.eql(string);
57
- expect(typeof decryptString).to.eql('string');
58
- });
59
-
60
- it('should be able to decrypt original object', () => {
61
- expect(decryptObject).to.be.eql(object);
62
- expect(typeof decryptObject).to.eql('object');
63
- });
64
-
65
- it('should be able to decrypt original number', () => {
66
- expect(decryptNumber).to.be.eql(number);
67
- expect(typeof decryptNumber).to.eql('number');
68
- });
69
-
70
- it('should be able to decrypt original boolean', () => {
71
- expect(decryptBoolean).to.be.eql(boolean);
72
- expect(typeof decryptBoolean).to.eql('boolean');
73
- });
74
- });
75
-
76
- describe('Error handling and validations', () => {
77
- it('should error when secret is not provided', () => {
78
- try {
79
- encrypt('nullSecret');
80
- } catch (error) {
81
- expect(error.message).equal('must be initialized with a secret key of type string');
82
- }
83
- });
84
-
85
- it('should error when non-string data is passed as decryption string', () => {
86
- try {
87
- const nonStringData = 12345;
88
- //@ts-ignore
89
- decrypt(nonStringData);
90
- } catch (error) {
91
- expect(error.message).equal('argument must be a string, or a string-like object');
92
- }
93
- });
94
-
95
- it('should error when a non string data type is to be decrypted', () => {
96
- try {
97
- const nonStringData: any = void(0);
98
- decrypt(nonStringData);
99
- } catch (error) {
100
- expect(error.message).equal('argument must be a string, or a string-like object');
101
- }
102
- });
103
-
104
- it('should error when a non string data type is to be decrypted', () => {
105
- try {
106
- decrypt(decryptNullData);
107
- } catch (error) {
108
- expect(error.message).equal('argument must be a string, or a string-like object');
109
- }
110
- });
111
-
112
- it('should throw an error when an undefined data is to be encrypted', () => {
113
- try {
114
- encrypt(undefined);
115
- } catch (error) {
116
- expect(error.message).equal('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
117
- }
118
- });
119
-
120
- it('should throw an error when an undefined data is to be encrypted', () => {
121
- try {
122
- encrypt(null);
123
- } catch (error) {
124
- expect(error.message).equal('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
125
- }
126
- });
127
-
128
- it('should throw an error when an null data is to be encrypted', () => {
129
- try {
130
- encrypt(encryptNullData);
131
- } catch (error) {
132
- expect(error.message).equal('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
133
- }
134
- });
135
- });