Giter VIP home page Giter VIP logo

cryptojs's Introduction

CryptoJS

This repo is straight unmodified-in-any-way copy of Google Code hosted CryptoJS project at https://code.google.com/p/crypto-js/ . This is hosted at github to add bower package so future updates can be managed better.

Directory Structure

You have two folders:

  • components
  • rollups

The files in rollups folder is concatenation of one or more files in components folder followed by minification. This makes files in rollups folder standalone includable in your projects without worrying about its dependencies. You can view relation between files in rollup and components here: https://code.google.com/p/crypto-js/source/browse/tags/3.1.2/builder/build.yml

Install

If you are not using bower then just include the .js file from rollups folder for whatever algorithm you want to use. UTF8 encoder is included in each rollup js. If you need UTF16 or Base64 encoder then also add corresponding files from components folder (see following example).

Using Bower:

bower install cryptojslib

APIs

You can play with below code live at http://jsbin.com/bubucixixi/1/edit?html,console.

Please see the Quick Start guide at https://code.google.com/p/crypto-js/#Quick-start_Guide

Below are very quick examples of core usage:

MD5

MD5 is a widely used hash function. It's been used in a variety of security applications and is also commonly used to check the integrity of files. Though, MD5 is not collision resistant, and it isn't suitable for applications like SSL certificates or digital signatures that rely on this property.

<script src="http://<mysite>/<libs location>/cryptojslib/rollups/md5.js"></script>
<script src="http://<mysite>/<libs location>/cryptojslib/components/enc-base64-min.js"></script>
<script>
	//The hash algorithms accept either strings or instances of CryptoJS.lib.WordArray.
	//A WordArray object represents an array of 32-bit words.
	//When you pass a string, it's automatically converted to a WordArray encoded as UTF-8.
    var hash = CryptoJS.MD5("Message");
	alert(hash.toString(CryptoJS.enc.Base64));
</script>
SHA-3

SHA-3 is the winner of a five-year competition to select a new cryptographic hash algorithm where 64 competing designs were evaluated.

<script src="http://<mysite>/<libs location>/cryptojslib/rollups/sha3.js"></script>
<script>
    var hash = CryptoJS.SHA3("Message");
	
	//The hash you get back isn't a string yet. It's a WordArray object.
	//When you use a WordArray object in a string context,
	//it's automatically converted to a hex string.	
	alert(hash.toString()); //Same as hash.toString(CryptoJS.enc.Hex);
</script>
Encoding and decoding

You can convert string to word arrays using various encoders. And word array in to string using decoders.

<script>
    var wordArray = CryptoJS.enc.Utf8.parse('𤭢');
    var utf8  = CryptoJS.enc.Utf8.stringify(wordArray);
    console.log(utf8);
</script>	

The UTF8 encoder/decoder is included in core.js and hence is available in rollup files for algorithms. However if you need UTF16 and Base64 encoder then you need to include corresponding file from components folder (see below for MD5 hash with Base64 example).

Using with AMD/RequireJS

CryptoJS does not have built-in support for AMD/RequireJS yet. However adding shims is almost trivial. For use with RequireJS, using files in components is probably more desirable instead of files in rollups folder because you probably already have setup RequireJS optimizer or other build process. To build the shim for RequireJS follow this steps:

Here's the example: Let's say we want to use MD5 with Base64 encoder. The shim would look like this

require.config({
    paths: {
        'cryptojs.core': "path/to/cryptojslib/components/core.js",
        'cryptojs.md5': "path/to/cryptojslib/components/md5.js",
        'cryptojs.base64': "path/to/cryptojslib/components/enc-base64.js"
    },
    shim: {
		'cryptojs.core': {
			exports: "CryptoJS"
		},
		'cryptojs.md5': {
			deps: ['cryptojs.core'],
			exports: "CryptoJS"	//You can also use "CryptoJS.MD5"
		},
		'cryptojs.base64': {
			deps: ['cryptojs.core'],
			exports: "CryptoJS"	//You can also use "CryptoJS.enc.Base64"
		}
    }
});

Copyrights

Please see copyrights.txt file in the root folder which is copy of corresponding file from Google Code project. This github repository does not assert any copyrights beyond what original CryptoJS does.

cryptojs's People

Contributors

demaniak avatar maxmillion avatar sytelus 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  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

cryptojs's Issues

Finding an exact decryption mechanism.

def encryption(payload_data, merchant)
key = merchant.api_secret_key
algorithm = 'AES-128-CBC'
begin
cipher = OpenSSL::Cipher.new(algorithm)
cipher.encrypt()
cipher.key = key
crypt = cipher.update(payload_data) + cipher.final()
crypt_string = (Base64.encode64(crypt))
rescue Exception => e
Rails.logger.info "encryption failed #{e.message}"
end
end

I tried the method described in https://code.google.com/archive/p/crypto-js/issues/91. But i couldnt decrypt the message. The above attached is the encryption mechanism I use in Ruby.

Cannot read property 'createDecryptor' of undefined

Hi

I'm trying to use the library to encrypt/decrypt aes messages but when I try to decrypt a message I got the message of the title.
This is what I try to do:

var key = CryptoJS.enc.Base64.parse(password);
var decryptedData = CryptoJS.AES.decrypt( response.token, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
} );

This are the loaded libraries:

<script src="../../ext-libs/crypto/core-min.js"></script> <script src="../../ext-libs/crypto/aes.js"></script> <script src="../../ext-libs/crypto/cipher-core-min.js"></script> <script src="../../ext-libs/crypto/enc-base64-min.js"></script> <script src="../../ext-libs/crypto/pbkdf2.js"></script> <script src="../../ext-libs/crypto/enc-utf16-min.js"></script>

Long ouput of AES-256 cipher

Why AES cipher with 256 bit key produced ciphertext of 48 bytes long?
(it should be 32 bytes long)

let encrypt = function(data, key) {
    let iv = new Uint8Array(16);
    window.crypto.getRandomValues(iv);

    let encKey = convert.ua2words(key, 32);
    let encIv = {
        iv: convert.ua2words(iv, 16)
    };
    let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Hex.parse(data), encKey, encIv);
    return {
        ciphertext: encrypted.ciphertext,
        iv: iv,
        key: key
    };
};

License

Can you update license please?

Maximum call stack size exceed in core.js

Line 226 of core.js : crash sometime for obscur reasons
(with chromium 50.0.2661.75 (64-bit))
(not with FireFox 46.0)
solved by changing

219             } else if (thatWords.length > 0xffff) {
220                 // Copy one word at a time
221                 for (var i = 0; i < thatSigBytes; i += 4) {
222                     thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
223                 }
224             } else {
225                 // Copy all words at once
226                 thisWords.push.apply(thisWords, thatWords);
227             }

by

219             } else {
220                 // Copy one word at a time
221                 for (var i = 0; i < thatSigBytes; i += 4) {
222                     thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
223                 }
224             }
Error : Uncaught RangeError: Maximum call stack size exceeded  
  C_lib.WordArray.Base.extend.concat  
  C_lib.BufferedBlockAlgorithm.Base.extend._append  
  C_lib.Hasher.BufferedBlockAlgorithm.extend.finalize  
  (anonymous function)  
  hashChunk  
  (anonymous function)

EDIT : fix can be done by lowering the word limit : passed from Oxffff to 0xfff

219             } else if (thatWords.length > 0xfff) {
220                 // Copy one word at a time
221                 for (var i = 0; i < thatSigBytes; i += 4) {
222                     thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
223                 }
224             } else {
225                 // Copy all words at once
226                 thisWords.push.apply(thisWords, thatWords);
227             }

Cannot install with npm

We are migrating from bower package manager to npm. And we have faced with issue that we cannot install cryptojslib as npm module.
Our package json file looks like next:
"dependencies": { "backbone": "~1.3.2", "codemirror": "5.29.0", "cryptojslib": "sytelus/CryptoJS.git#v3.1.2", }
As you can see we want to install cryptojslib from github repository with specific tag version.
While npm installing we realized that we cannot install cryptojslib package via npm because cryptojslib repository has no package.json file. Please add this file to github repository.

Difference in output of java's crypt lib and crypto-js

This is the java code. I am trying to replicate the same functionality in javascript.

public String populateHMAC(String app_id, String mobile, String token,
String deviceId) {

String hmac = null;
try {
    CryptLib cryptLib = new CryptLib();
    String message = app_id + "|" + mobile + "|" + deviceId;
    byte[] tokenBytes = Base64.decode(token, 2);//cryptLib.hexStringToByteArray(token);

    String temp=Base64.encodeToString(cryptLib.SHA256(message),2);

    byte[] tempArr=Base64.decode(temp,2);

    byte[] hmacBytes = cryptLib.encrypt(
            cryptLib.SHA256(message),
            tokenBytes);
    hmac = Base64.encodeToString(hmacBytes, Base64.DEFAULT);
} catch (Exception e) {
    e.printStackTrace();
}
return hmac;

}
These are the functions inside CryptLib

The SHA256 function

 public byte[] SHA256(String paramString) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(paramString.getBytes("UTF-8"));
byte[] digest = md.digest();
return digest;

}
And the encrypt function

public byte[] encrypt(byte[] data, byte[] key) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
byte[] iv = new byte[16];
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher acipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] arrayOfByte1;
acipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
arrayOfByte1 = acipher.doFinal(data);
return arrayOfByte1;

}
This is the javascript code for the same functionality. I am using the crypto-js library.

        var crypto = require('crypto-js');

        populateHMAC( app_id,  mobile, token, deviceId){

        var rawStr = token;
        var wordArray = crypto.enc.Utf8.parse(rawStr);
        var base64 = crypto.enc.Base64.stringify(wordArray);

        var enctoken=btoa(token);


        var message= app_id + "|" + mobile + "|" + deviceId;

        var decodedString= atob(enctoken);

        message=encodeURIComponent(message);

        var hash= crypto.SHA256(message);//.toString(crypto.enc.Utf8);

        console.log("params",decodedString,hash.toString(crypto.enc.Hex));


        var iv = crypto.enc.Hex.parse('0000000000000000'); 
        var encryptedString = crypto.AES.encrypt(hash, decodedString, {
                    iv:iv,
                    mode: crypto.mode.CBC,
                    padding: crypto.pad.Pkcs7
                });

        var encodedString= encryptedString.ciphertext.toString(crypto.enc.Base64);


         return encodedString;
        }

The two outputs are different and I am unable to figure out why.

wiredep and the main property of bower.json

As noted here in this issue, cryptojslib defines **/*.js in the main property. When grunt-wiredep comes across this, it parse it into your html like so:

<script src="bower_components/cryptojslib/**/*.js"></script>

Any package that lists this library as a dependency will ultimately have this same issue. If you can't point to a specific file in your main then I suggest note defining the main property at all. That way, grunt-wiredep will throw a warning, stating that it was unable to wire up said dependency and to wire it up manually. It's better to see that warning than to have **/*.js added to the HTML.

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.