Socket
Socket
Sign inDemoInstall

ncrypt-js

Package Overview
Dependencies
10
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.0 to 1.1.0

src/utils.ts.BAK

14

dist/index.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./src/utils");
exports.encrypt = utils_1.encrypt;
exports.decrypt = utils_1.decrypt;
exports.default = {
encrypt: utils_1.encrypt,
decrypt: utils_1.decrypt,
};
const ncrypt_1 = __importDefault(require("./src/ncrypt"));
exports.ncrypt = ncrypt_1.default;
module.exports = ncrypt_1.default;
exports.default = ncrypt_1.default;
//# sourceMappingURL=index.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
class Ncrypt {
constructor(text, secret) {
/**
* object constructor
* @param text
* @param secret
*/
constructor(secret) {
/**

@@ -25,39 +31,47 @@ * convert all entered text to decimal equivalent character codes

};
this.secret = secret;
this.text = text;
}
/**
* process data to be encrypted
* @param {}
* @returns {string.<string>} encoded string data
*/
encodeData() {
const data = this.text;
if (data == void 0)
throw new Error('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
/**
* this does the actual processing return a string
* resulting from charCode conversion, salting and
* hexadecimal mapping
* process data to be encrypted
* @param {}
* @returns {string.<string>} encoded string data
*/
return data.split('')
.map(this.convertTextToDecimal)
.map(this.applySecretToCharacters)
.map(this.convertByteToHexadecimal)
.join('');
this.encrypt = (data) => {
/**
* this does the actual processing return a string
* resulting from charCode conversion, salting and
* hexadecimal mapping
*
*/
// if (data == void 0) throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
try {
const encodedMessage = JSON.stringify(data).split('')
.map(this.convertTextToDecimal)
.map(this.applySecretToCharacters)
.map(this.convertByteToHexadecimal)
.join('');
return utils_1.encode(encodedMessage);
}
catch (error) {
throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
}
};
/**
* decodes encoded string resulting from util encryption
* @param {string.<stirng>} encodeData
* @returns {decodedData.<string>} decoded data
*/
this.decrypt = (text) => {
const encodeData = utils_1.decode(text);
const data = encodeData.match(/.{1,2}/g)
.map((hex) => parseInt(hex, 16))
.map(this.applySecretToCharacters)
.map((charCode) => String.fromCharCode(charCode))
.join('');
const arr = [];
arr.push(data);
return JSON.parse(data);
};
this.secret = secret;
}
/**
* decodes encoded string resulting from util encryption
* @param {string.<stirng>} encodeData
* @returns {decodedData.<string>} decoded data
*/
decodeData(encodeData) {
return encodeData.match(/.{1,2}/g)
.map((hex) => parseInt(hex, 16))
.map(this.applySecretToCharacters)
.map((charCode) => String.fromCharCode(charCode))
.join('');
}
}
exports.default = Ncrypt;
//# sourceMappingURL=ncrypt.js.map

@@ -6,9 +6,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = __importDefault(require("crypto"));
const ncrypt_1 = __importDefault(require("./ncrypt"));
const crypto_1 = __importDefault(require("crypto")); // this is necessary for some version of nodejs without crypto module
const algorithm = 'aes-256-cbc';
/**
* crypto random key generated from core node {crypto} module
*/
const key = crypto_1.default.randomBytes(32);
/**
* crypto random initial vector generated from core node {crypto} module

@@ -18,88 +14,38 @@ */

/**
* secret key {secret}
* crypto random key generated from core node {crypto} module
*
* {note}: please read the value for KEY from your app's environment
*/
let _secret, exitProcess = process.exit;
const _key = process.env.KEY || 'please provide a KEY in your .env file or config';
const key = crypto_1.default.scryptSync(_key, 'salt', 32);
/**
* sets the value of the secret
* @param {secret.<string>} secret
*/
const setSecret = (secret) => {
_secret = secret;
};
/**
* intermediate data encoder function
* @param string
* @param {string.<any>} text
* @param secret
* @returns {object} encrypted, cipher
* @returns {string} encrypted or cipher text
*/
const encoder = (string, secret) => {
const encryptObject = new ncrypt_1.default(string, secret);
const encoded = encryptObject.encodeData();
const cipher = crypto_1.default.createCipheriv('aes-256-cbc', Buffer.from(key), initialVector);
let encrypted = cipher.update(encoded);
return { encrypted, cipher };
};
/**
* intermediate data decoder function
* @param string
* @param secret
* @returns {object} encrypted, cipher
* @throws {Error} Error
*/
const decoder = (decryptionInitialVector, encodedText) => {
try {
const _iv = Buffer.from(decryptionInitialVector, 'hex');
const encryptedText = Buffer.from(encodedText, 'hex');
const decipher = crypto_1.default.createDecipheriv('aes-256-cbc', Buffer.from(key), _iv);
let decrypted = decipher.update(encryptedText);
return { decrypted, decipher };
}
catch (error) {
throw new Error('argument must be a string, or a string-like object');
}
};
/**
*
* @param {text.<object, string, *>} text
* @param {secret.<string>} secret
* @returns {data.<string>} crypto-cipher encrypted data and concatenated initial vector string
*/
const encrypt = (data, secret) => {
if (data === null)
throw new Error('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
setSecret(secret);
const string = JSON.stringify(data);
if (typeof secret !== 'string')
throw new Error('must be initialized with a secret key of type string');
/**
* ncrypt constructor with initial data and secret {secret}
*/
let { encrypted, cipher } = encoder(string, secret);
exports.encode = (text) => {
let cipher = crypto_1.default.createCipheriv(algorithm, Buffer.from(key), initialVector);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
/**
* concatenated data and vector string
*/
return `${initialVector.toString('hex')}.${encrypted.toString('hex')}`;
};
exports.encrypt = encrypt;
/**
* decrypt crypto-ciphered data and vector
* @param {encodedData.<any>} encodedData
* intermediate data decoder function
* @param {string.<any>} text
* @returns {string.<string>} decrypted data
*/
const decrypt = (encodedData) => {
if (typeof encodedData !== 'string') {
exports.decode = (text) => {
if (typeof text !== 'string') {
throw new TypeError('argument must be a string, or a string-like object');
}
const encryptObject = new ncrypt_1.default(encodedData, _secret);
const decryptionInitialVector = encodedData.split('.')[0];
const encodedText = encodedData.split('.')[1];
let { decrypted, decipher } = decoder(decryptionInitialVector, encodedText);
const iv = text.split('.')[0];
const encryptedData = text.split('.')[1];
let _iv = Buffer.from(iv, 'hex');
let encryptedText = Buffer.from(encryptedData, 'hex');
let decipher = crypto_1.default.createDecipheriv(algorithm, Buffer.from(key), _iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
/**
* JSON parsed decrypted text buffer
*/
return JSON.parse(encryptObject.decodeData(decrypted.toString()));
return decrypted.toString();
};
exports.decrypt = decrypt;
//# sourceMappingURL=utils.js.map

@@ -1,14 +0,7 @@

import {
encrypt,
decrypt
} from './src/utils';
import ncrypt from './src/ncrypt';
module.exports = ncrypt;
export default ncrypt;
export {
encrypt,
decrypt,
ncrypt
}
export default {
encrypt,
decrypt,
}
{
"name": "ncrypt-js",
"version": "1.0.0",
"version": "1.1.0",
"description": "a light weight javascript data encryption and decryption library",

@@ -8,3 +8,3 @@ "main": "dist/index.js",

"start": "npm run build && node dist/index",
"start:dev": "tsc -w index.ts",
"start:dev": "ts-node index.ts",
"clean": "rm -rf dist",

@@ -41,16 +41,21 @@ "prepare": "npm run build",

"devDependencies": {
"@types/chai": "^4.2.0",
"@types/chai": "^4.2.10",
"@types/mocha": "^5.2.7",
"@types/node": "^12.7.2",
"@types/node": "^12.12.29",
"chai": "^4.2.0",
"coveralls": "^3.0.6",
"cross-env": "^5.2.0",
"crypto": "^1.0.1",
"mocha": "^6.2.0",
"coveralls": "^3.0.9",
"cross-env": "^5.2.1",
"mocha": "^6.2.2",
"mocha-istanbul": "^0.3.0",
"mocha-lcov-reporter": "^1.3.0",
"nyc": "^14.1.1",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
"ts-node": "^8.6.2",
"typescript": "^3.8.3"
},
"dependencies": {
"crypto": "^1.0.1",
"dotenv": "^8.2.0",
"handlebars": "^4.7.3",
"simple-crypto-js": "^2.2.0"
}
}
# NcryptJs
[![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) [![License](https://img.shields.io/github/license/ajimae/ncrypt-js)](#license)
[![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)
[![Release](https://img.shields.io/github/v/release/ajimae/ncrypt-js)](https://github.com/ajimae/ncrypt-js/releases) [![size](https://img.shields.io/github/languages/code-size/ajimae/ncrypt-js)](https://img.shields.io/github/languages/code-size/ajimae/ncrypt-js) [![issues](https://img.shields.io/github/issues/ajimae/ncrypt-js)](https://img.shields.io/github/issues/ajimae/ncrypt-js)
**_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.
<!-- ```diff
- const ReduxThunk = require('redux-thunk')
+ const ReduxThunk = require('redux-thunk').default
``` -->

@@ -58,9 +60,9 @@ ## Contents

```javascript
```diff
// ES6 and later
import ncrypt from "ncrypt-js";
import * as ncrypt from "ncrypt-js";
+ import ncrypt from "ncrypt-js";
- import * as ncrypt from "ncrypt-js";
// or
import { encrypt, decrypt } from "ncrypt-js";
- import { encrypt, decrypt } from "ncrypt-js";
```

@@ -70,8 +72,8 @@

```javascript
```diff
// ES5 and older
var ncrypt = require("ncrypt-js");
+ var ncrypt = require("ncrypt-js");
// or
var { encrypt, decrypt } = require("ncrypt-js");
- var { encrypt, decrypt } = require("ncrypt-js");
```

@@ -92,3 +94,3 @@

| ------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **encrypt()** | Encrypts data. |**data**: _object/string/number/boolean_ - The data to be encrypted. <br/> **secret**: _string_ - The secret (key or password) that will be used as the salt for the encryption process. |**ciphered**: _string_ - encrypted data. |
| **encrypt()** | Encrypts data. |**data**: _object/string/number/boolean_ - The data to be encrypted. <br/>|**ciphered**: _string_ - encrypted data. |
| **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).

@@ -98,14 +100,20 @@

### Using `encrypt()` and `decrypt()` functons
### Using `encrypt()` and `decrypt()` functons - As of version 1.1.0 this is deprecated, an object must be created first.
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.
```javascript
var { encrypt, decrypt } = require("ncrypt-js");
```diff
- var { encrypt, decrypt } = require("ncrypt-js");
+ var ncrypt = require("ncrypt-js");
var data = "Hello World!";
var _secretKey = "some-super-secret-key";
+ var { encodeData, decodeData } = new ncrypt(_secretKey);
// encrypting super sensitive data here
var encryptedData = encrypt(data, _secretKey);
- var encryptedData = encrypt(data, _secretKey);
+ var encryptedData = encrypt(data);
console.log("Encryption process...");

@@ -119,3 +127,3 @@ console.log("Plain Text : " + data);

console.log("Decipher Text : " + decryptedData);
console.log("... done.");
console.log("...done.");
```

@@ -131,4 +139,6 @@

var ncryptObject = new ncrypt(_secretKey);
// encrypting super sensitive data here
var encryptedData = ncrypt.encrypt(data, _secretKey);
var encryptedData = ncryptObject.encrypt(data);
console.log("Encryption process...");

@@ -139,6 +149,6 @@ console.log("Plain Text : " + data);

// decrypted super encrypted string here
var decryptedData = ncrypt.decrypt(encryptedData);
var decryptedData = ncryptObject.decrypt(encryptedData);
console.log("... and then decryption...");
console.log("Decipher Text : " + decryptedData);
console.log("... done.");
console.log("...done.");
```

@@ -162,4 +172,6 @@

var ncryptObject = new ncrypt('ncrypt-js');
// encrypting super sensitive data here
var encryptedObject = ncrypt.encrypt(object, _secretKey);
var encryptedObject = ncryptObject.encrypt(object);
console.log("Encryption process...");

@@ -170,6 +182,6 @@ console.log("Plain Object : " + object);

// decrypted super encrypted string here
var decryptedObject = ncrypt.decrypt(encryptedObject);
var decryptedObject = ncryptObject.decrypt(encryptedObject);
console.log("... and then decryption...");
console.log("Decipher Text : " + decryptedObject);
console.log("... done.");
console.log("...done.");
```

@@ -176,0 +188,0 @@

@@ -6,4 +6,4 @@

convertByteToHexadecimal(number: number): string;
encodeData(): string;
decodeData(data: string): string;
encrypt(text: object | string | number | boolean): string;
decrypt(data: string): string;
}
import { INcrypt } from './ncrypt.d';
import { encode, decode } from './utils';

@@ -16,6 +17,9 @@ export default class Ncrypt implements INcrypt {

private text: string;
constructor(text: string, secret: string) {
/**
* object constructor
* @param text
* @param secret
*/
constructor(secret: string) {
this.secret = secret;
this.text = text;
}

@@ -51,6 +55,3 @@

*/
encodeData() {
const data: string = this.text;
if (data == void 0) throw new Error('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
encrypt = (data: object | string | number | boolean) => {
/**

@@ -60,8 +61,16 @@ * this does the actual processing return a string

* hexadecimal mapping
*
*/
return data.split('')
.map(this.convertTextToDecimal)
.map(this.applySecretToCharacters)
.map(this.convertByteToHexadecimal)
.join('');
// if (data == void 0) throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
try {
const encodedMessage = JSON.stringify(data).split('')
.map(this.convertTextToDecimal)
.map(this.applySecretToCharacters)
.map(this.convertByteToHexadecimal)
.join('');
return encode(encodedMessage);
} catch (error) {
throw new Error('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
}
}

@@ -74,9 +83,16 @@

*/
decodeData(encodeData: string) {
return encodeData.match(/.{1,2}/g)
.map((hex: any) => parseInt(hex, 16))
.map(this.applySecretToCharacters)
.map((charCode: any) => String.fromCharCode(charCode))
.join('')
decrypt = (text: string) => {
const encodeData = decode(text);
const data = encodeData.match(/.{1,2}/g)
.map((hex: any) => parseInt(hex, 16))
.map(this.applySecretToCharacters)
.map((charCode: any) => String.fromCharCode(charCode))
.join('');
const arr = [];
arr.push(data);
return JSON.parse(data);
}
}

@@ -1,8 +0,4 @@

import crypto from 'crypto';
import Ncrypt from './ncrypt';
import crypto from 'crypto'; // this is necessary for some version of nodejs without crypto module
/**
* crypto random key generated from core node {crypto} module
*/
const key: Buffer = crypto.randomBytes(32);
const algorithm = 'aes-256-cbc';

@@ -15,69 +11,20 @@ /**

/**
* secret key {secret}
* crypto random key generated from core node {crypto} module
*
* {note}: please read the value for KEY from your app's environment
*/
let _secret: string, exitProcess = process.exit;
const _key = process.env.KEY || 'please provide a KEY in your .env file or config';
const key: Buffer = crypto.scryptSync(_key, 'salt', 32);
/**
* sets the value of the secret
* @param {secret.<string>} secret
*/
const setSecret = (secret: string) => {
_secret = secret;
}
/**
* intermediate data encoder function
* @param string
* @param {string.<any>} text
* @param secret
* @returns {object} encrypted, cipher
* @returns {string} encrypted or cipher text
*/
const encoder = (string: string, secret: string) => {
const encryptObject: Ncrypt = new Ncrypt(string, secret);
const encoded: string = encryptObject.encodeData();
const cipher: crypto.Cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), initialVector);
let encrypted: Buffer = cipher.update(encoded);
return { encrypted, cipher };
}
export const encode = (text: string) => {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), initialVector);
let encrypted = cipher.update(text);
/**
* intermediate data decoder function
* @param string
* @param secret
* @returns {object} encrypted, cipher
* @throws {Error} Error
*/
const decoder = (decryptionInitialVector: string, encodedText: string) => {
try {
const _iv: Buffer = Buffer.from(decryptionInitialVector, 'hex');
const encryptedText: Buffer = Buffer.from(encodedText, 'hex');
const decipher: crypto.Decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), _iv);
let decrypted: Buffer = decipher.update(encryptedText);
return { decrypted, decipher };
} catch (error) {
throw new Error('argument must be a string, or a string-like object');
}
}
/**
*
* @param {text.<object, string, *>} text
* @param {secret.<string>} secret
* @returns {data.<string>} crypto-cipher encrypted data and concatenated initial vector string
*/
const encrypt = (data: object | string | number | boolean, secret: string) => {
if (data === null) throw new Error('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
setSecret(secret);
const string: string = JSON.stringify(data);
if (typeof secret !== 'string') throw new Error('must be initialized with a secret key of type string');
/**
* ncrypt constructor with initial data and secret {secret}
*/
let { encrypted, cipher }: { encrypted: Buffer; cipher: crypto.Cipher } = encoder(string, secret);
encrypted = Buffer.concat([encrypted, cipher.final()]);
/**
* concatenated data and vector string
*/
return `${initialVector.toString('hex')}.${encrypted.toString('hex')}`;

@@ -87,23 +34,22 @@ }

/**
* decrypt crypto-ciphered data and vector
* @param {encodedData.<any>} encodedData
* intermediate data decoder function
* @param {string.<any>} text
* @returns {string.<string>} decrypted data
*/
const decrypt = (encodedData: string) => {
if (typeof encodedData !== 'string') {
export const decode = (text: string) => {
if (typeof text !== 'string') {
throw new TypeError('argument must be a string, or a string-like object');
}
const encryptObject: Ncrypt = new Ncrypt(encodedData, _secret);
const decryptionInitialVector = encodedData.split('.')[0];
const encodedText = encodedData.split('.')[1];
let { decrypted, decipher }: { decrypted: Buffer; decipher: crypto.Decipher; } = decoder(decryptionInitialVector, encodedText);
const iv = text.split('.')[0];
const encryptedData = text.split('.')[1];
let _iv = Buffer.from(iv, 'hex');
let encryptedText = Buffer.from(encryptedData, 'hex');
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), _iv);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
/**
* JSON parsed decrypted text buffer
*/
return JSON.parse(encryptObject.decodeData(decrypted.toString()));
return decrypted.toString();
}
export { encrypt, decrypt };
import * as chai from "chai";
import * as ncrypt from '../index';
import ncrypt from '../index';
const expect = chai.expect;
const { encrypt, decrypt } = ncrypt;

@@ -12,14 +11,17 @@ const object = {

};
const string = "ncrypt-js is great.";
const number = 19960404;
const boolean = false;
const string: string = "ncrypt-js is great.";
const number: number = 19960404;
const boolean: boolean = false;
const _nullData: any = null;
const _secret = 'shhh its a secret';
const _nullSecret: any = null;
const encryptString = encrypt(string, _secret);
const encryptNumber = encrypt(number, _secret);
const encryptObject = encrypt(object, _secret);
const encryptBoolean = encrypt(boolean, _secret);
const { encrypt, decrypt } = new ncrypt(_secret);
const encryptString = encrypt(string);
const encryptNumber = encrypt(number);
const encryptObject = encrypt(object);
const encryptBoolean = encrypt(boolean);
const encryptNullData = encrypt(_nullData);
const decryptString = decrypt(encryptString);

@@ -29,2 +31,3 @@ const decryptNumber = decrypt(encryptNumber);

const decryptBoolean = decrypt(encryptBoolean);
const decryptNullData = encrypt(_nullData);

@@ -78,3 +81,3 @@ describe('Encrytion', () => {

try {
encrypt('nullSecret', _nullSecret);
encrypt('nullSecret');
} catch (error) {

@@ -87,3 +90,4 @@ expect(error.message).equal('must be initialized with a secret key of type string');

try {
const nonStringData = '["string"]';
const nonStringData = 12345;
//@ts-ignore
decrypt(nonStringData);

@@ -103,8 +107,16 @@ } catch (error) {

});
it('should error when a non string data type is to be decrypted', () => {
try {
decrypt(decryptNullData);
} catch (error) {
expect(error.message).equal('argument must be a string, or a string-like object');
}
});
it('should throw an error when an undefined data is to be encrypted', () => {
try {
encrypt(undefined, _secret);
encrypt(undefined);
} catch (error) {
expect(error.message).equal('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
expect(error.message).equal('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
}

@@ -115,3 +127,3 @@ });

try {
encrypt(null, _secret);
encrypt(null);
} catch (error) {

@@ -121,2 +133,10 @@ expect(error.message).equal('no data was entered, enter data of type object, number, string or boolean to be encrypted.');

});
it('should throw an error when an null data is to be encrypted', () => {
try {
encrypt(encryptNullData);
} catch (error) {
expect(error.message).equal('invalid data was entered, enter data of type object, number, string or boolean to be encrypted.');
}
});
});

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc