Giter VIP home page Giter VIP logo

simple-crypto-js's Introduction

SimpleCrypto

GitHub Release Build Distribution Coverage Status Dependencies Status

NPM Version License Monthly Downloads

SimpleCrypto is a JavaScript library that simplify the process of encryption and decryption of JavaScript objects, as simple as just calling encrypt() and decrypt() function. This library implements brix's crypto-js library. This library is pure JavaScript library built with TypeScript targeting CommonJS ECMAScript 5 (ES5), so it is compatible with most NodeJS back-end applications or JavaScript front-end (client browser).

Breaking Changes

v2.3.0: New Algorithm

SimpleCrypto v2.3.0 onward will use a new algorithm, because the older one was vulnerable to chosen cipher attack. Any data that encrypted using v2.2.0 and earlier will NOT be able to be decrypted using v2.3.0 onward; vice versa: data encrypted using v2.3.0 onward will NOT be able to be decrypted using v2.2.0 and earlier.

v3.0.0: New Native Crypto Module

SimpleCrypto v3.0.0 onward will use new crypto-js dependency version ^4.0.0. This version of crypto-js replaces Math.random() method with native crypto module. Because of this, SimpleCrypto might not be able to run on some environments without native crypto module support, such as IE 10 (and earlier) or React Native.

Please read more here.

List of Contents

What's New?

What's New in 3.0.1 (latest current)

  • Upgrade crypto-js dependency to version 4.1.1.
  • Improving typings.

What's New in 2.5.1 (latest legacy)

  • Improving typings.

For full change-log, please refer to CHANGELOG file.

Getting Started

This library is available through jsDelivr CDN and package manager (like npm or yarn).

Vanilla JavaScript + HTML

To get started, add SimpleCrypto script to your HTML page. Only legacy version of SimpleCrypto is supported.

<head>
    <!-- Another line -->
    <script src="//cdn.jsdelivr.net/npm/simple-crypto-js@legacy/dist/SimpleCrypto.min.js"></script>
    <!-- Another line -->
</head>

Then, your script section, you may use SimpleCrypto as Class to create a new SimpleCrypto instance.

<body>
<!-- Another line -->
<script lang="js">
    var simpleCrypto = new SimpleCrypto("a very secret key")
    <!-- Do your cryptographic logic here  -->
</script>
<!-- Another line -->
</body>

NodeJS

If you are using NodeJS, add simple-crypto-js as your project dependency.

# If you're using NPM
npm install --save simple-crypto-js

# If you're using Yarn
yarn add simple-crypto-js

Then, include SimpleCrypto your project.

var SimpleCrypto = require("simple-crypto-js").default

If you are using Babel or TypeScript that support import statement, you could go that way.

import SimpleCrypto from "simple-crypto-js"

How to Use SimpleCrypto

Full documentation about SimpleCrypto API is available here.

Built With

Written in TypeScript, built into ECMAScript 5 using the TypeScript compiler and webpack bundler.

Contribution

To contribute, simply fork this project, and issue a pull request. However, before issuing a pull request, you have to make sure that your changes will not break current API, its parameter and its expected output.

You may test your changes by running the test script.

npm run test

If all tests were passed, you are good to go.

Version Management

We use Semantic Versioning for version management. For the versions available, see the tags on this repository.

Authors

  • Danang Galuh Tegar Prasetyo - Initial work - danang-id

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE file for details

Acknowledgments

  • This library was developed to support and simplify the Secure Cookies library.
  • Made available by open source and of course brix's crypto-js library

simple-crypto-js's People

Contributors

adi928 avatar danang-id avatar dependabot[bot] avatar huntr-helper avatar lamike310 avatar transmissions11 avatar vezul avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

simple-crypto-js's Issues

SimpleCrypto is Vulnerable to Chosen-Ciphertext Attacks

public encrypt(data: object | string | number | boolean): string {
if (data == void 0) {
throw new Error('No data was attached to be encrypted. Encryption halted.');
}
const string: string = typeof data == "object"
? JSON.stringify(data)
: typeof data == "string" || typeof data == "number" || typeof data == 'boolean'
? data.toString()
: null;
if (null === string) {
throw new Error('Only object, string, number and boolean data types that can be encrypted.');
}
const salt: string | WordArray = SimpleCrypto.generateRandom(128, true);
const key: WordArray = PBKDF2(this._secret, salt, {
keySize: this._keySize / 32,
iterations: this._iterations
});
const initialVector: string | WordArray = SimpleCrypto.generateRandom(128, true);
const encrypted: WordArray = AES.encrypt(string, key, {
iv: initialVector as string,
padding: pad.Pkcs7,
mode: mode.CBC
});
return salt.toString() + initialVector.toString() + encrypted.toString();
}

SimpleCrypto implements AES-CBC with PKCS#7 padding, which is vulnerable to chosen-ciphertext attacks, specifically a padding oracle attack.

These vulnerabilities in CBC mode have been public for 17 years (since Serge Vaudenay published a paper about it in 2002).

Recommendation: Migrate to one of the following...

  1. XChaCha20-Poly1305
  2. AES-GCM-SIV
  3. AES-GCM

Ubuntu 22.04.2 LTS

We upgraded our sever to Ubuntu version 22.04.2 and now library has stopped working we are using version 3.0.1 . Its gives us an error
simplecrypto Invalid encrypted text received. Decryption halted. Even though the string was encrypted by the same key that we are using to decrypt

Unable make it work with Remix

I'm on a Remix project, I added simple crypto through pnpm then on top of my file I just added

import SimpleCrypto from "simple-crypto-js";

const secretKey = "some-unique-key";
const crypto = new SimpleCrypto(secretKey);

But this doesn't work properly with Remix build

 info  rebuilding... (~ app/routes/_tools.qr-code-time-tracking.tsx)
 info  rebuilt (496ms)
TypeError: SimpleCrypto is not a constructor
    at file:///...website/app/routes/_tools.qr-code-time-tracking.tsx:12:16
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

Do you know what could be going on right now?

Type error when using Typescript

Hi,

I recently tried to use your library for a project, but encountered issues while compiling with strict-mode on:

node_modules/simple-crypto-js/src/SimpleCrypto.ts:9:22 - error TS7006: Parameter 'secret' implicitly has an 'any' type.

9   public constructor(secret) {
                       ~~~~~~

node_modules/simple-crypto-js/src/SimpleCrypto.ts:23:11 - error TS2322: Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.

23     const string: string = typeof data == "object" ? JSON.stringify(data) : typeof data == "string" || typeof data == "number" || typeof data == 'boolean' ? data.toString() : null;
             ~~~~~~

node_modules/simple-crypto-js/src/SimpleCrypto.ts:31:77 - error TS2345: Argument of type '{ iv: string | WordArray; padding: Padding; mode: Mode; }' is not assignable to parameter of type 'CipherOption'.
  Types of property 'iv' are incompatible.
    Type 'string | WordArray' is not assignable to type 'string | undefined'.
      Type 'WordArray' is not assignable to type 'string'.

 31     const encrypted: CryptoJS.WordArray = CryptoJS.AES.encrypt(string, key, {
                                                                                ~
 32       iv: initialVector,
    ~~~~~~~~~~~~~~~~~~~~~~~~
...
 34       mode: CryptoJS.mode.CBC
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 35     });
    ~~~~~

I have created a MR to fix these issues, and other small issues :)

Big numbers don't work

const simpleCrypto = new SimpleCrypto('a very secret key')
const a = simpleCrypto.encrypt(76561198028033919)
simpleCrypto.decrypt(a) // 76561198028033920 

0 gets removed when encrypting a number string with leading 0

When encrypting and decrypting a string with a leading 0, it removes the 0.

import SimpleCrypto from "simple-crypto-js"

let simpleCrypto = new SimpleCrypto("hYLiR5U1g2ppct1Aw8hf");
let encrypted = simpleCrypto.encryptObject("0419383728");
console.log(encrypted);

let decrypted = simpleCrypto.decrypt(encrypted);
console.log(decrypted + typeof decrypted);

output

419383728number

How do I determine the IV being used?

I am sending the data to a PHP server that will also know the secret key. How do I determine the IV being used since IV is a requirement for AES-CBC?

Typescript: failed to parse source map

I'm getting this annoying warning when compiling from React Typescript:

Compiled with warnings.

Failed to parse source map from '.../node_modules/simple-crypto-js/src/SimpleCrypto.ts' file: Error: ENOENT: no such file or directory, open '.../node_modules/simple-crypto-js/src/SimpleCrypto.ts'

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

WARNING in ./node_modules/simple-crypto-js/lib/SimpleCrypto.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '.../node_modules/simple-crypto-js/src/SimpleCrypto.ts' file: Error: ENOENT: no such file or directory, open '.../node_modules/simple-crypto-js/src/SimpleCrypto.ts'

There is a source map for JS file. My best guess is that the source map file for SimpleCrypto.ts TS file is missing.

Malformed UTF-8 data

I am reading a .mp4 file and encrypting it using the library and writing it as a .dat file. I am accessing the .dat file and streaming 4,000,000 characters at a time till the end. While streaming, i am decrypting the data on go. So, the first set of characters are decrypting succcessfully using this method

var decipherText = simpleCrypto.decrypt(chunk)

while the next set of characters throw Malformed UTF-8 data error.

Not working anymore in React Native / Expo

Hi,

Since I updated from 2.2.0 to 2.4, my Expo (React Native) app, stopped working properly, throwing this error on decrypt:

The package at "node_modules/crypto-js/core.js" attempted to import the Node standard library module "crypto". It failed because React Native does not include the Node standard library. Read more at https://docs.expo.io/versions/latest/introduction/faq/#can-i-use-nodejs-packages-with-expo
Failed building JavaScript bundle.

Any idea how to fix that?

Does this use a Pepper?

I'm not very good with understanding crypto but have created a pouchdb plugin for my project.

I'd like to know if pepper is used in this lib.
(I couldn't find it in a variable by the name pepper.)

Cannot use namespace 'WordArray' as a type - TypeScript 3

Hi Guys ... I am trying to use simple-crypto-js lib in my angular app but while installing the package via npm i ... I am getting below Typescript errors - Cannot use namespace 'WordArray' as a type.

Below are the version details:
Angular 7
Typescript 3.2
Simple-crypto-js 2.3

Any help or guidance would be highly appreciated. Thank you!

image

How to change cipherText length

There any way to change the number of encrypt plainText, like put the cipherText length to 20 or any other number of caracther ?
And do the decrypt with this cipherText with length to 20 or any other number of caracther

compatible with react-native?

Hi Is simple-crypto-js compatible with react-native? i.e if I encrypt a string in nodejs (server) and try to decrypt it in react-native, it it gauranteed to work at all times?

Invalid encrypted text received. Decryption halted

Hello,

May I please ask for your assistance to the following issue? Not sure if it is related to simple-crypto-js or not, but I would appreciate your comments.

Version I am using: 3.0.1

Steps to reproduce the error:

  • I’m using indexedDb to save my apps data in the browser. When user closes the apps, indexedDb data is converted to blob, then in base64, and finally I stringify it.
  • The resulted string is now encrypted using simple-crypto-js. It is stored again on indexedDb.
  • To decrypt, I get the encrypted text from indexedDb first, and do the decryption which works fine most of the time. However, not sure why, I do receive the invalid encrypted text error message without any version change at all. (Not sure if it is because I am encrypting a large amount of chars) causes the decryption to fail.)

PS: I have already tried and explore the latest suggestion in this issue as well without success.

Thank you.

Differents behavior on differents env

Hi,

I'm having another issue.

• I have an API server, using Node / Express which uses your lib to encrypt data and put this encrypted data into a QR Code
• I have a mobile app (React Native) which reads those QR Code and decrypt data using the same version of your lib, and the same code : they actually share the same JS module

Few days ago, the strangest thing happened. My Express app have 3 envs : local, develop, production.
• on local, QR codes are working, data is encrypted (by my local server) and decrypted (by the mobile app) successfully
When I log my simpleCrypto instance after setting it with a secret key and encrypted data, it returns something like this :
{"_secret":"my-secret","_keySize":256,"_iterations":100,"_defaultEncoder":{}}
• on production, QR codes are working, data is encrypted (by my local server) and decrypted (by the mobile app) successfully
• on develop, Qr codes looks differents, and when I log simpleCrypto instance, with the same code (it actually is the same branch) it returns :
{"_dataBuffer":"my-text-to-encrypt","_encoder":{},"_secret":{"words":[1411654652,1498173583,-882117861,-1761465478,-1507164864,-1303364673,-1856803349,-526043043,-333785183,190184971,-1097709156,1104822113,-274110398,1746094063,-1976477165,-629992992],"sigBytes":64},"_keySize":256,"_iterations":100}

What I don't understand is that my local and the dev have the same package.json, same package-json.lock, same Node version, same code, but simpleCrypto instances objects are not the same, and I really have no clue what can cause this.

It's more a question than an issue... But I'm looking for any idea :)

Empty string encryption

The line here prevents us from encrypting an empty string, even though it was possible before 2.4.0?

if (data === void 0 || data === null || data === "") {

I understand the reasoning behind this (as to prevent silly errors by developers), but this actually complicates my use case of doing E2EE, as live editing forms where users may clear a form, will throw an error.

Is there anyway I could make a PR that would disable this protection or at least add an an optional parameter to disable it?

BUG: SimpleCrypto sees two numbers at the beginning of a string and encrypts it as a number, cutting off the rest of the string.

Hey SimpleCrypto team,

I've been using this library for a while now, and was excited to see a new release, but my tests are failing as I've found a little bug in the type detection.

If I encrypt this string: 97c9fadd9deefa0e3594d79e6b86b55bb4906fc2ae21956ca09cdd51e6827a1e using this function:

 const simpleCrypto = new SimpleCrypto(password);

 return simpleCrypto.encrypt(data);

and decrypt it using:

 try {
    const simpleCrypto = new SimpleCrypto(password);

    return simpleCrypto.decrypt(text);
  } catch {
    return undefined;
  }

I will get back the number 97 in number form (not string).

If you need help reproducing, I can create a codesandbox or something, but this is a pretty easy to repo issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.