Skip to content

Commit

Permalink
Merge pull request #3 from ajimae/ch-update-readme-#0003
Browse files Browse the repository at this point in the history
#3 Update README and package.json File
  • Loading branch information
ajimae authored Aug 27, 2019
2 parents 9374fd7 + db67348 commit 94de7d1
Show file tree
Hide file tree
Showing 5 changed files with 264 additions and 23 deletions.
192 changes: 190 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,193 @@
# ncrypt-js
# 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)

A light weight plain text encoder and decoder
**_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.


## Contents

* [NcryptJs](#NcryptJs)
* [Contents](#contents)
<!-- * [Changes Log (What's New)](#changes-log-whats-new) -->
* [Getting Started](#getting-started)
* [Installation](#installation)
* [Documentation](#documentation)
* [NcryptJs Functions](#ncryptjs-functions)
* [Using `encrypt()` and `decrypt()`](#using-encrypt-and-decrypt)
* [Using default imports](#Using-default-imports)
<!-- * [Change the Secret Key](#change-the-secret-key)
* [Object Encryption](#object-encryption)
* [Random Key Generator](#random-key-generator) -->
* [Built With](#built-with)
* [Contribution](#contribution)
* [Version Management](#version-management)
* [Authors](#authors)
* [License](#license)
* [Acknowledgments](#acknowledgments)

<!-- ## Changes Log (What's New)
**What's New in 2.2.0**
* Fix CDN release, setting webpack output as UMD with default library name of SimpleCrypto.
* CDN now have two file you may use, the distribution file and minified distribution one.
For full changelog, please refers to [CHANGELOG](CHANGELOG.md) file. -->

## Getting Started

This library is available through these javascript node package manager [npm](https://www.npmjs.org/) and [yarn](https://www.yarnpkg.com/).

## Installation

To use this library, first ensure you have a package manager initialized either with [npm](https://www.npmjs.org/) or [yarn](https://www.yarnpkg.com/)

```bash
# for npm use:
npm install --save ncrypt-js

# for yarn use:
yarn add ncrypt-js
```

To include **_ncrypt-js_** in your project. use one of these:

```javascript
// ES6 and later
import ncrypt from "ncrypt-js";
import * as ncrypt from "ncrypt-js";

// or
import { encrypt, decrypt } from "ncrypt-js";
```

However, if you are using ECMAScript 5 and older, use the require statement:

```javascript
// ES5 and older
var ncrypt = require("ncrypt-js");

// or
var { encrypt, decrypt } = require("ncrypt-js");
```

## Documentation

**_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).

### NcryptJs Functions


### List of **_NcryptJs_** functions.



| Functions | Description | Parameters | Return |
| ------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **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. |
| **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).



### Using `encrypt()` and `decrypt()` functons

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");

var data = "Hello World!";
var _secretKey = "some-super-secret-key";

// encrypting super sensitive data here
var encryptedData = encrypt(data, _secretKey);
console.log("Encryption process...");
console.log("Plain Text : " + data);
console.log("Cipher Text : " + encryptedData);

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

### Using default imports

```javascript
var ncrypt = require("ncrypt-js");

var data = "Hello World!";
var _secretKey = "some-super-secret-key";

// encrypting super sensitive data here
var encryptedData = ncrypt.encrypt(data, _secretKey);
console.log("Encryption process...");
console.log("Plain Text : " + data);
console.log("Cipher Text : " + encryptedData);

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

### Object Encryption

Encryption and decryption of JavaScript object literal has never been simpler than this.

To encrypt and decrypt JavaScript object literal, simply use `encrypt()` and `decrypt()` function from an instance. This will use AES-CBC encryption algorithm.


```javascript
var ncrypt = require("ncrypt-js");

var _secretKey = "some-super-secret-key";
var object = {
NycryptJs: "is cool and fun.",
You: "should try it!"
}

// encrypting super sensitive data here
var encryptedObject = ncrypt.encrypt(object, _secretKey);
console.log("Encryption process...");
console.log("Plain Object : " + object);
console.log("Encrypted Object : " + encryptedObject);

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

## Built With

Written in [TypeScript](https://typscriptlang.org/), built into ECMAScript 5 using the TypeScript compiler.

## Contribution

To contribute, simply fork this project, and issue a pull request.

## Version Management

We use [SemVer](http://semver.org/) for version management. For the versions available, see the [tags on this repository](https://github.com/ajimae/ncrypt-js/tags).

## Authors

* **Chukwuemeka Ajima** - _Initial work_ - [ajimae](https://github.com/ajimae)

<!-- Feel free to include a CONTRIBUTORS.md file and modify this contributors secion -->
<!-- See also the list of [contributors](CONTRIBUTORS) who participated in this project. -->

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details

## Acknowledgments

* This library was developed to simplify how data is encrypted and decrypted in javascript.
* Made available by open source and special thanks to [Shahid](https://twitter.com/codeforgeek) for his super simple [article](https://codeforgeek.com/encrypt-and-decrypt-data-in-node-js/) on node core encryption (crypto) library.
* Thanks to [danang-id](https://github.com/danang-id) whose [README](https://github.com/danang-id/simple-crypto-js/blob/master/README.md) was very insightful and [Jorgeblom](https://stackoverflow.com/users/2861702/jorgeblom) for his custom cipher algorithm on this stackoverflow [answer](https://stackoverflow.com/a/54026460/4907157)
5 changes: 4 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { encrypt, decrypt } from './src/utils';
import {
encrypt,
decrypt
} from './src/utils';

export {
encrypt,
Expand Down
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
"name": "ncrypt-js",
"version": "1.0.0",
"description": "a light weight javascript data encryption and decryption library",
"main": "index.ts",
"main": "dist/index.js",
"scripts": {
"start": "tsc --outDir dist && node dist/index",
"start": "npm run build && node dist/index",
"start:dev": "tsc -w index.ts",
"clean": "rm -rf dist",
"prepare": "npm run build",
"build": "tsc --outDir dist",
"test": "cross-env TS_NODE_FILES=true nyc mocha --exit --require ts-node/register --colors test/**/*.ts",
"coverage": "nyc report --reporter=text-lcov | coveralls"
},
Expand Down
62 changes: 46 additions & 16 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const initialVector: Buffer = crypto.randomBytes(16);
/**
* secret key {secret}
*/
let _secret: string;
let _secret: string, exitProcess = process.exit;


/**
Expand All @@ -25,25 +25,55 @@ const setSecret = (secret: string) => {
_secret = secret;
}

/**
* intermediate data encoder function
* @param string
* @param secret
* @returns {object} encrypted, cipher
*/
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 };
}

/**
* 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 = function (text: object | string | number | boolean, secret: string) {
if (text === null) throw new Error('no data was entered, enter data of type object, number, string or boolean to be encrypted.');
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 data: string = JSON.stringify(text);
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}
*/
const encryptObject: Ncrypt = new Ncrypt(data, 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);
let { encrypted, cipher }: { encrypted: Buffer; cipher: crypto.Cipher } = encoder(string, secret);
encrypted = Buffer.concat([encrypted, cipher.final()]);

/**
Expand All @@ -55,17 +85,17 @@ const encrypt = function (text: object | string | number | boolean, secret: stri
/**
* decrypt crypto-ciphered data and vector
* @param {encodedData.<any>} encodedData
* @returns {string.<string>} decrypted text
* @returns {string.<string>} decrypted data
*/
const decrypt: any = function (encodedData: string) {
const decrypt = (encodedData: string) => {
if (typeof encodedData !== '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];

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);

let { decrypted, decipher }: { decrypted: Buffer; decipher: crypto.Decipher; } = decoder(decryptionInitialVector, encodedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);

/**
Expand Down
22 changes: 20 additions & 2 deletions test/ncrypt.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ const expect = chai.expect;
const { encrypt, decrypt } = ncrypt;

const object = {
SimpleCrypto: "is great.",
NcryptJs: "is great.",
You: "should try it!"
};
const string = "SimpleCrypto is great.";
const string = "ncrypt-js is great.";
const number = 19960404;
const boolean = false;

Expand Down Expand Up @@ -79,6 +79,24 @@ describe('Error handling and validations', () => {
}
});

it('should error when non-string data is passed as decryption string', () => {
try {
const nonStringData = '["string"]';
decrypt(nonStringData);
} catch (error) {
expect(error.message).equal('argument must be a string, or a string-like object');
}
});

it('should error when a non string data type is to be decrypted', () => {
try {
const nonStringData: any = void(0);
decrypt(nonStringData);
} 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);
Expand Down

0 comments on commit 94de7d1

Please sign in to comment.