Giter Club home page Giter Club logo

crypto-es's People

Contributors

dependabot[bot] avatar entronad avatar juchar avatar powerkiki avatar trasherdk 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

crypto-es's Issues

TripleDES decryption compatibility issues with CryptoJS

Hi, we would like to update from CryptoJS to CryptoES but unfortunately we got compatibility issue with TripleDES decryption. Text that was encrypted with CryptoJS can not be decrypted with CryptoES. I've created two stackblitz examples that demonstrates problem.

CryptoJS (4.2.0) TripleDES encryption:
stackblitz

CryptoES (2.1.0) TripleDES decryption (with ciphertext from previous stackblitz)
stackblitz

I've looked to some other similar issues and something tells me this might be a configuration issue (wrong keySize, or blockSize...), but I don't really know how to change these settings or if it's completely other issue.

ReferenceError: window is not defined when importing CryptoES with the newer 2.0.0 version

Whenever I import CryptoES and rebuild my API it throws this error:

const crypto = globalThis?.crypto || global?.crypto || window?.crypto || self?.crypto || frames?.[0]?.crypto;
                                                       ^
ReferenceError: window is not defined

Using crypto-es version 2.0.0.
Project is a backend API using Fastify, pure JS, no TypeScript involved.

Just tested with previous 1.2.7 version and this error isn't thrown.

Can provide more details if needed, just let me know what you need.

Testing with Jest

Hi,

I'm using crypto-es in an angular (v12) project, and it works fine. However when I run the test I get this error:

Details:
    /.../node_modules/crypto-es/lib/enc-base64.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import {
                                                                                                                                                 ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { HttpParams } from '@angular/common/http';
      2 | import { Injectable } from '@angular/core';
    > 3 | import { Base64 } from 'crypto-es/lib/enc-base64.js';
        | ^
      4 | import { SHA256 } from 'crypto-es/lib/sha256.js';

I try already a couple of day's to solve this issue, but without any success.

Thanks

Distribution for non ES6 environments

Hi, this is a great library, however, it is missing an ES2015 compatible distribution on NPM. Are there any plans on adding a transpilation step before publishing this to npm?

Context: We'd like to use this in TS/Angular project that targets ES2015 for compatibility but really cannot, because there is no (easy) way to transpile an external library during the ng build process.

Compatibility of encryption with CryptoJS

Hi, i'm using CryptoJS and I've been thinking about switching to CryptoES, but unfortunately my old encrypted data in CryptoJS can't be decrypted with the same password for CryptoES.

In my process i used TripleDES, Base64, and main AES function where set options are iv, padding and mode.
For both(CryptoJS, CryptoES) is process and options same.

I dont have passwords, and implement system which use both to swap is a lot of work for a small profit.
Is there some different default, or there is no native way to switch from CryptoJS to CryptoES without data loss (for example because some of named functions returns different results for CryptoES/CryptoJS)?

Unable to ng-build-prod

Hello,

I've used this package in Angular 7 codebase and it is working fine when I run the project.

However, when I try to ng --build the code, I get the following error:

ERROR in modules-login-login-module-ngfactory.0e87ddf2fd23f5d113c2.js from Terser Unexpected token: punc ()) [./node_modules/crypto-es/lib/evpkdf.js:41,0][modules-login-login-module-ngfactory.0e87ddf2fd23f5d113c2.js:1318,4]

In the above error message, login_module is the component in which I've implemented the logic.

I've updated the compiler options as suggested, but still the error doesn't go.

Please advise.

TypeError: wordArray.clamp is not a function #41

// TypeError: wordArray.clamp is not a function #41

// Receiving this error when trying to Base64 encode an encryption result like this:

const encrypted_content: string = CryptoES.AES.encrypt( content, password ).toString( CryptoES.enc.Base64 );

// It works when I don't pass any formatter to the toString() function:

const encrypted_content: string = CryptoES.AES.encrypt( content, password ).toString();

// The same (unresolved) issue already exists in the CryptoJS library:

// To address this issue,

const encrypted_content = CryptoES.AES.encrypt(content, password).toString();
const base64Encoded = CryptoES.enc.Base64.stringify(CryptoES.enc.Utf8.parse(encrypted_content));

// OR you use this

const base64EncodedCipherText = Buffer.from(cipherText, 'binary').toString('base64');

Cannot read property 'call' of undefined at AESAlgo.reset (cipher-core.js:458)

`import CryptoES from "crypto-es";

/**

  • @word 要加密的内容
  • @Keyword String 服务器随机返回的关键字
    */
    export function aesEncrypt(word: string, keyWord: string = "XwKsGlMcdPMEhR1B") {
    var key = CryptoES.enc.Utf8.parse(keyWord);
    var srcs = CryptoES.enc.Utf8.parse(word);
    var encrypted = CryptoES.AES.encrypt(srcs, key, {
    mode: new CryptoES.mode.ECB(),
    padding: CryptoES.pad.Pkcs7,
    });
    return encrypted.toString();
    }`

not working with openssl

OpenSSL 1.1.1i

openssl enc -aes-256-cbc -in infile -out outfile -pass pass:"Secret Passphrase" -e -base64

Decrypt with CryptoES Got Nothing
CryptoES.AES.decrypt(openSSLEncrypted, "Secret Passphrase");

Decrypt with OpenSSL Works Well
openssl aes-256-cbc -d -in outfile -out outfile.txt -pass pass:"Secret Passphrase"

TS Error: keySize does not exist in type 'CipherCfg'

CryptoJS.AES.decrypt(str, _key, {
    keySize: 16, // <---- Argument of type '{ keySize: number; iv: WordArray; mode: typeof ECB; padding: Padding; }' is not assignable to parameter of type 'CipherCfg'.
                 //       Object literal may only specify known properties, and 'keySize' does not exist in type 'CipherCfg'.ts(2345)
    iv: _iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString(CryptoJS.enc.Utf8)

export all encodings for partial import

Is it possible to export all other encodings (specially enc.Utf8) so they can be used as partial import and eventually help webpack to exclude all un-imported packages?

no types

👋 hello! thanks for this wonderful library!

i'm running into the problem that typescript complains that no typings are found

import {MD5} from "crypto-es/lib/md5.js"
 //               ^^
 // Could not find a declaration file for module

crypto-es does not yet appear to have a tsconfig.json configured to emit declaration files like "md5.d.ts" alongside each module

a possible solution would be to add a tsconfig.json which configures "declaration": true

{
  "compilerOptions": {
    "declaration": true
  }
}

TypeError: wordArray.clamp is not a function

Receiving this error when trying to Base64 encode an encryption result like this:

const encrypted_content: string = CryptoES.AES.encrypt( content, password ).toString( CryptoES.enc.Base64 );

It works when I don't pass any formatter to the toString() function:

const encrypted_content: string = CryptoES.AES.encrypt( content, password ).toString();

The same (unresolved) issue already exists in the CryptoJS library:

brix/crypto-js#189

Falling back to `Math.random()` even if polyfill is used

I've first encountered this when using expo (react-native) where I have to polyfill the globalThis.crypto with the following code right at the very beginning of my App.js:

import { getRandomValues as expoCryptoGetRandomValues } from 'expo-crypto';

class Crypto {
  getRandomValues = expoCryptoGetRandomValues;
}

const webCrypto = typeof crypto !== 'undefined' ? crypto : new Crypto();

export function polyfillWebCrypto() {
  if (typeof crypto === 'undefined') {
    Object.defineProperty(globalThis, 'crypto', {
      configurable: true,
      enumerable: true,
      get: () => webCrypto,
    });
  }
}

Even though the polyfill is applied you still end up getting the Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used message in the logs. I think the reason for this is that the randomWordArray function is declared in such a way that it will only evaluated once during the initialization, but I wasn't able to find a order of operations during which the polyfill is already applied before this.

It's probably a bit less efficient, but you could get around this issue if you would define randomWordArray in core.js instead in the following way:

const randomWordArray = (nBytes) => {
  const crypto =
    (typeof globalThis != 'undefined' ? globalThis : void 0)?.crypto ||
    (typeof global != 'undefined' ? global : void 0)?.crypto ||
    (typeof window != 'undefined' ? window : void 0)?.crypto ||
    (typeof self != 'undefined' ? self : void 0)?.crypto ||
    (typeof frames != 'undefined' ? frames : void 0)?.[0]?.crypto;

  if (crypto) {
    const words = [];

    for (let i = 0; i < nBytes; i += 4) {
      words.push(crypto.getRandomValues(new Uint32Array(1))[0]);
    }

    return new WordArray(words, nBytes);
  }

  console.warn('Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used');
  const words = [];
  
  const r = (m_w) => {
    let _m_w = m_w;
    let _m_z = 0x3ade68b1;
    const mask = 0xffffffff;

    return () => {
      _m_z = (0x9069 * (_m_z & 0xFFFF) + (_m_z >> 0x10)) & mask;
      _m_w = (0x4650 * (_m_w & 0xFFFF) + (_m_w >> 0x10)) & mask;
      let result = ((_m_z << 0x10) + _m_w) & mask;
      result /= 0x100000000;
      result += 0.5;
      return result * (Math.random() > 0.5 ? 1 : -1);
    };
  };

  for (let i = 0, rcache; i < nBytes; i += 4) {
    const _r = r((rcache || Math.random()) * 0x100000000);

    rcache = _r() * 0x3ade67b7;
    words.push((_r() * 0x100000000) | 0);
  }

  return new WordArray(words, nBytes);
}

Is this anything you would consider changing?

Hashing/Decrypting bug

Hashing decrypted data seems to fail when data isn't a multiple of 4 bytes (i.e. whole words). This can be fixed by clamping the WordArray, but I'm not sure if this is a bug with the Hashers or the Decryptors. See Jest test below:

import CryptoES from 'crypto-es';

describe('hashing/decrypting bug', () => {
  const data11Bytes = 'hello world';
  const data11BytesHash = CryptoES.SHA256(data11Bytes).toString();

  // clamp will remove the last word and 0 the last byte of word 2
  const decrypted11Bytes = new CryptoES.lib.WordArray(
    [
      1751477356, // 68656C6C
      1864398703, // 6F20776F
      1919706117, // 726C6405
      84215045, // 05050505
    ],
    11,
  );
  const decrypted11BytesClamped = new CryptoES.lib.WordArray(
    [
      1751477356, // 68656C6C
      1864398703, // 6F20776F
      1919706112, // 726C6400
    ],
    11,
  );
  const data12Bytes = 'hello world!';
  const data12BytesHash = CryptoES.SHA256(data12Bytes).toString();

  test('hash of decrypted 11 bytes is wrong without clamping', () => {
    const key = CryptoES.lib.WordArray.random(32);
    const iv = CryptoES.lib.WordArray.random(32);

    const encryptor = CryptoES.algo.AES.createEncryptor(key, {iv});
    const encryptedData = encryptor.finalize(data11Bytes);

    const decryptor = CryptoES.algo.AES.createDecryptor(key, {iv});
    const decryptedData = decryptor.finalize(encryptedData);
    expect(decryptedData).toEqual(decrypted11Bytes);
    const decryptedDataHash = CryptoES.SHA256(decryptedData).toString();

    // FAIL - SHOULD BE EQUAL.
    expect(decryptedDataHash).not.toEqual(data11BytesHash);
  });
  test('hash of decrypted 12 bytes is correct without clamping', () => {
    const key = CryptoES.lib.WordArray.random(32);
    const iv = CryptoES.lib.WordArray.random(32);

    const encryptor = CryptoES.algo.AES.createEncryptor(key, {iv});
    const encryptedData = encryptor.finalize(data12Bytes);

    const decryptor = CryptoES.algo.AES.createDecryptor(key, {iv});
    const decryptedData = decryptor.finalize(encryptedData);
    const decryptedDataHash = CryptoES.SHA256(decryptedData).toString();

    // SUCCESS
    expect(decryptedDataHash).toEqual(data12BytesHash);
  });
  test('hash of decrypted 11 bytes is correct with clamping', () => {
    const key = CryptoES.lib.WordArray.random(32);
    const iv = CryptoES.lib.WordArray.random(32);

    const encryptor = CryptoES.algo.AES.createEncryptor(key, {iv});
    const encryptedData = encryptor.finalize(data11Bytes);

    const decryptor = CryptoES.algo.AES.createDecryptor(key, {iv});
    const decryptedData = decryptor.finalize(encryptedData);

    expect(decryptedData).toEqual(decrypted11Bytes);
    decryptedData.clamp();
    expect(decryptedData).toEqual(decrypted11BytesClamped);

    expect(decryptedData).not.toEqual(decrypted11Bytes);
    const decryptedDataHash = CryptoES.SHA256(decryptedData).toString();

    // SUCCESS
    expect(decryptedDataHash).toEqual(data11BytesHash);
  });
});

Error in Electron: "Must use import to load ES Module"

I was using Electron to write a native application, but reported an error after introducing crypto-es in the Node layer. In the provided npm package, can you distinguish the following usage methods, such as:

{
  "main": "dist/index.cjs.js",
  "module": "dist/index.esm.js"
}

Crypto-ES examples doesn't compile with VSC / Typescript

I originally wrote some Javascript code using Crypto-ES and got everything working nicely.However after changing the file extension from .js to .tsx my code no longer compiles - there's a problem being indicated with the use of CryptoES.mode.CBC.

I tried copying/pasting the following example code from the usage section at https://www.npmjs.com/package/crypto-es
and there is the same problem. It says "Type 'typeof CFB' is missing the following properties from type 'BlockCipherMode': mixIn ... Did you mean to use 'new' with this expression?"

const encrypted = CryptoES.AES.encrypt("Message", "Secret Passphrase", { mode: CryptoES.mode.CFB, padding: CryptoES.pad.AnsiX923 });

How can I proceed to fix the problem?

AES encrypt is very slow.

Data below is very slow, it takes about 26 seconds to encrypt 8mb data.
I also submited the data as attacment

import React from 'react';
import CryptoES from 'crypto-es';
import Base64 from './base64';

let start = null;
class speedtest{

    static start(txt){

        start = Date.now();

        if( txt !== undefined )
            console.log(txt);
    }

    static end(txt){

        console.log(txt, ((Date.now() - start) / 1000) + " seconds");
    }
}


export default class Ws_crypto {

    static mac_hash = null;

    static sign(data) {

        speedtest.start('CRYPTO');

        if (!Ws_crypto.mac_hash)
            return {'data': null, mac: null};

        let key_string = Ws_crypto.mac_hash;
        let iv_string = CryptoES.lib.WordArray.random(16).toString();
        let mac_string = null;
        let encrypted_string = null;

        speedtest.end('CCC-1');

        let encHex = CryptoES.enc.Hex;
        let aes = CryptoES.AES;
        let Pkcs7 = CryptoES.pad.Pkcs7;

        speedtest.end('CCC-2');

        // the key and iv should be 32 hex digits each, any hex digits you want, but it needs to be 32 on length each
        let key = encHex.parse(key_string);
        let iv = encHex.parse(iv_string);
        try {

            //data = JSON.parse(data);
        } catch (error) {

        }
        let data_string = typeof data == 'object' ? JSON.stringify(data) : data;

        speedtest.end('CCC-3');//above takes 13 seconds total time


        // encrypt the message
        encrypted_string = aes.encrypt(data_string, key, {
            iv: iv,
            padding: Pkcs7,
            mode: CryptoES.mode.CBC
        }).toString();
        speedtest.end('CCC-4');//above takes 26 seconds total time
        mac_string = CryptoES.HmacSHA256(encrypted_string, key).toString(CryptoES.enc.Hex);

        speedtest.end('CCC-5');

        let ret = {'data': data_string, 'mac': Base64.btoa(mac_string + iv_string)};

        speedtest.end('CCC-6');
        return ret;
    }
}

_data.txt

Issue importing it on Typescript

I can't seem to find how to import the modules to use in typescript:

I tried all formats but all givens an error:

import { MD5 } from 'crypto-es';
Errors:
node_modules/crypto-es/lib/index.d.ts:19:21 - error TS2370: A rest parameter must be of an array type.

19 static create(...args?: Array): Base;
~~~~~~~~~~~~~~~~~~~~
node_modules/crypto-es/lib/index.d.ts:634:18 - error TS2417: Class static side 'typeof PasswordBasedCipher' incorrectly extends base class static side 'typeof SerializableCipher'.
Types of property 'encrypt' are incompatible.
Type '(cipher?: Cipher | undefined, message?: string | WordArray | undefined, password?: string | undefined, cfg?: object | undefined) => CipherParams' is not assignable to type '(cipher?: Cipher | undefined, message?: string | WordArray | undefined, key?: WordArray | undefined, cfg?: object | undefined) => CipherParams'.
Types of parameters 'password' and 'key' are incompatible.
Type 'WordArray | undefined' is not assignable to type 'string | undefined'.
Type 'WordArray' is not assignable to type 'string'.

import CryptoES from 'crypto-es';
Errors:
Same errors

Typescript version: Version 3.7.4

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "lib": ["DOM"],
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "strict": true,
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "es2017",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "inlineSourceMap": false,
    "outDir": "dist",
    "baseUrl": ".",
    "typeRoots": ["src/application/types", "node_modules/@types"]
  },
  "include": [
    "src/**/*",
    "src/**/*.json"
  ]
}

Wrong typing expected in the hasher for PBKDF2

Typescript complains, but it works:

CryptoES.PBKDF2(..., { hasher: CryptoES.algo.SHA1 });

Typescript accepts this but it doesn't work:

CryptoES.PBKDF2(..., { hasher: new CryptoES.algo.SHA1() });

I'm guessing the type expected for hasher should be something like this:

new (...args: any) => CryptoES.lib.Hasher;

skipLibCheck doesn't appear to be needed

Hi, thanks for the fork I want to use it to fix es-related issues (core.js not found warning).

I was reading the README and it doesn't seem I need to use skipLibCheck what was your issue? Should we remove this from the README?

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.