Giter Club home page Giter Club logo

jshashes's Introduction

jsHashes Build Status NPM version

jshashes is lightweight library implementing the most extended cryptographic hash function algorithms in pure JavaScript (ES5 compliant).

The goal is to provide an dependency-free, fast and reliable solution for hash algorithms for both client-side and server-side JavaScript environments. The code is fully compatible with the ECMAScript 5 specification and is used in production in browsers and node.js/io.js

If you are looking for a low-level performance library for the server-side, note that node.js/io.js provides its own native module: crypto

Supported hash algorithms

Additional functionalities

Environments

  • Browsers (ES3)
  • node.js/io.js (all versions)
  • Rhino
  • RingoJS

Usage

Each algorithm has its respective own instantiable object. Here you can see an example of how to create a new instance for each one:

// new MD5 instance
var MD5 = new Hashes.MD5
// new SHA1 instance
var SHA1 = new Hashes.SHA1
// new SHA256 instance
var SHA256 =  new Hashes.SHA256
// new SHA512 instace
var SHA512 = new Hashes.SHA512
// new RIPEMD-160 instace
var RMD160 = new Hashes.RMD160

An example of how to generate an hexadecimal-based hash encoding for each algorithm:

// sample string
var str = 'Sample text!'
// output to console
console.log('MD5: ' + MD5.hex(str))
console.log('SHA1: ' + SHA1.hex(str))
console.log('SHA256: ' + SHA256.hex(str))
console.log('SHA512: ' + SHA512.hex(str))
console.log('RIPEMD-160: ' + RMD160.hex(str))

Browsers

This is a simple implementation for a client-side environment:

<html>
<head>
<script type="text/javascript" src="src/hashes.js"></script>
<script type="text/javascript">
// sample string
var str = 'This is a sample text!'
// new MD5 instance and hexadecimal string encoding
var MD5 = new Hashes.MD5().hex(str)
// output into DOM
document.write('<p>MD5: <b>' + MD5 + '</b></p>')
</script>
</head>
<body>
</body>
</html>

node.js / io.js

// require the module
var Hashes = require('jshashes')
// sample string
var str = 'This is a sample text!'
// new SHA1 instance and base64 string encoding
var SHA1 = new Hashes.SHA1().b64(str)
// output to console
console.log('SHA1: ' + SHA1)

Command-line interface

You can use the simple command-line interface to generate hashes.

$ hashes sha1-hex This is a sample string
> b6a8501d8a70e74e1dc12a6082102622fdc719bb

# or with quotes
$ hashes sha1-hex "This is a sample string"
> b6a8501d8a70e74e1dc12a6082102622fdc719bb

For more information about the options supported, type:

$ hashes -h

Installation

Via npm

$ npm install jshashes

Via Bower:

$ bower install jshashes

Via Component:

$ component install h2non/jshashes

Or loading the script directly:

http://cdn.rawgit.com/h2non/jsHashes/master/hashes.js

Public methods

Each algorithm class provides the following public methods:

  • hex(string) - Hexadecimal hash encoding from string.
  • b64(string) - Base64 hash encoding from string.
  • any(string,encoding) - Custom hash algorithm values encoding.
  • hex_hmac(key,string) - Hexadecimal hash with HMAC salt key.
  • b64_hmac(key,string) - Base64 hash with HMAC salt key.
  • any_hmac(key,string,encoding) - Custom hash values encoding with HMAC salt key support.
  • vm_test() - Simple self-test to see is working. Returns this Object.
  • setUpperCase(boolean) - Enable/disable uppercase hexadecimal returned string. Returns this Object.
  • setPad(string) - Defines a custom base64 pad string. Default is '=' according with the RFC standard. Returns this Object.
  • setUTF8(boolean) - Enable/disable UTF-8 character encoding. Returns this Object.

Hash encoding formats supported

  • Hexadecimal (most extended)
  • Base64
  • Custom hash values any() method

Benchmark

Node.js 0.6.18 running on a VPS Intel I7 930 with 512 MB of RAM (see server/benchmark.js)

Simple benchmark test generating 10000 hashes for each algorithm.
String: "A0gTtNtKh3RaduBfIo59ZdfTc5pTdOQrkxdZ5EeVOIZh1cXxqPyexKZBg6VlE1KzIz6pd6r1LLIpT5B8THRfcGvbJElwhWBi9ZAE"

* MD5
** Done in: 205 milliseconds
* SHA1
** Done in: 277 milliseconds
* SHA256
** Done in: 525 milliseconds
* SHA512
** Done in: 593 milliseconds
* RMD160
** Done in: 383 milliseconds

See client/benchmark.html for client-side.

Notes

  • Don't support checksum hash for files on the server-side, only strings-based inputs are supported.
  • It has not been planned to include support for more hash algorithms.
  • The goal is to provide the same JavaScript code in both server and client side, so it isn't planned to improve it in other ways.
  • Only Node.js server-side was tested, so with minimal changes, you can setup jsHashes in other server-side JS environment.

Changelog

  • 1.0.7
    • Merge #37: fix terminator statement token.
  • 1.0.6
    • Fix #34: options pad typo.
  • 1.0.4
    • Fix CLI script call error when use it from Bash
    • Added CLI usage example
  • 1.0.3
    • Important bugfixes to UTF-8 encoding (broken in 1.0.2) and the RIPEMD-160 hash (broken in 1.0.1). (gh #6)
    • New test suite for hashes, CRC32, and hmac; run with 'npm test' in node.
    • Fixed global variable leaks. (gh #13)
    • CRC32 will now always return positive values. (gh #11)
    • Added package version property to the exposed Hashes Object
    • Updated CLI script utility supporting all algorithms (see bin/hashes)
    • Fixed UTF-8 encoding/decoding error (if input parameter is undefined or invalid)
  • 1.0.2
    • Performance improvements and minimal refactor (length property caching, literal notation)
    • Available from Bower package manager
  • 1.0.1
    • Refactoring (hoisting, coercion, removed redundant functions, scoping, restructure...)
    • Performance improves
    • JSLint validation (except bitwise operators)
    • Now the library can be used like a AMD CommonJS module
    • Updated documentation
    • New folders structure
    • Added closure compiled and minimized library version
    • Available from Jam package manager
  • 0.1.5b
    • Added index.js for easy call the module in Node.js
    • Updated documentation
  • 0.1.4b
    • Now declaring objects using Literal Notation.
    • Solved syntax errors on minimized version (jshashes.min.js)
    • Added benchmark test and sample
  • 0.1.3b
    • Starting non-redundancy code refactorization
    • Added Helpers Object with some global functions
    • Added native support for Base64 provided as class
    • Added CRC-32 calculation support
    • Added URL encode/decode helpers functions
  • 0.1.2b
    • SHA1 error fixed.
    • General code changes (renaming classes, private methods, new methods...).
    • Changing library namespace to 'Hashes'.
    • Starting code documentation.
    • Added new examples of how to use.
  • 0.1.1b
    • Minimal library improvements.
    • There has been added some samples, like how to use it and support for NPM package.
  • 0.1.0b
    • First release: the code is stable, but the library is still beta and must be improved and documented.

TODO

  • Performance benchmarking

Authors

Library author

Original algorithm authors

Other contributors

License

jsHashes is released under New BSD license. See LICENSE file.

Issues

Feel free to report any issue you experiment via Github https://github.com/h2non/jsHashes/issues.

jshashes's People

Contributors

0xflotus avatar ben-ekw avatar bitdeli-chef avatar cecchi avatar cscott avatar dependabot[bot] avatar fish2000 avatar geopic avatar geriano avatar h2non avatar njlg 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

jshashes's Issues

SHA-384 support

Hi, I'm working on a project that I'd like to support SHA-384. Any plans to implement this?

Clarify examples folder names

Hi! The current example subfolders "client" and "server" make it look like this would be a client/server application. From the code it looks more like the "client" scripts are meant to run in web browsers, so how about we rename that folder to "web" or "html" or "browser-native"?

The "server" scripts seem meant to be run in a CommonJS environment such as Node.js, so how about we name that folder "cjs"? I recommend not to use "cli" or "node", because there are frameworks that enable browsers to load CommonJS modules (no build step required).

Hashes.Helpers.urlEncode function

What does the Hashes.Helpers.urlEncode and Hashes.Helpers.urlDecode used for exactly? I mean do they mimic encodeURI or encodeURIComponent or are these encodes specifically for use within the hash (as they are thus called helper functions)

Modularization

This is a great package, and thank you so much for it! However, I think it could be improved if each algorithm was it's own file, for those of us who only need one or two different algorithms.

Then, the build process could concatenate all the files and your bower.json could remain the same, but overrides could be specified as necessary, e.g.

"overrides": {
  "jshashes": {
    "main": "sha256.js"
  }
}

What do you think?

Can you support the OpenHarmony version?

I am developing an OpenHarmony application and have JavaScript compatibility issues. Can you support the OpenHarmony version? I am willing to participate in the development of adaptation and look forward to reply.

Path to /usr/bin/env wrong in bin/hashes.js

The bin/hashes.js in the NPM package (which seems to be missing from this repository) has the path to /usr/bin/env on the first line.

It should also probably have execute permissions.

Split algorithms into separate modules

Would be really nice if we could include only the hashing algorithms we need.

If you only need MD5, it would be nice to be able to exclude SHA1, SHA256, SHA512, CRC32 etc etc.

Wrong base64 encode of unicode chars

Base64 encode/decode of unicode chars first tries to convert to utf8, right idea but wrong implementation.

(new Hashes.Base64()).encode('张')
"5Q=="
(new Hashes.Base64()).setUTF8(false).encode(unescape(encodeURIComponent('张')))
"5byg"
window.btoa(unescape(encodeURIComponent('张')))
"5byg"

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding#The_.22Unicode_Problem.22

Implementation wise utf8Encode() returns same as unescape(encodeURIComponent()) so the problem is elsewhere. See https://github.com/davidchambers/Base64.js/blob/master/base64.js for window.atob() shim. I think len shoud be after utf8 encode.

Also base 64 decode is wrong.

(new Hashes.Base64()).decode('5byg')
"o("
(new Hashes.Base64()).setUTF8(false).decode('5byg')
"o("
decodeURIComponent(escape(window.atob("5byg")))
"张"

'any' encofing fails

I'm executing:

new Hashes.SHA256().any('test', "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()_-+={}|[]\\:\";'<>?,./")

which give me A-*A_[Hza*ek.e]hlq*%VwLgH0zDi-?4);_0tbQk,
but I'm expecting something like -*A_[Hza*ek.e]hlq*%VwLgH0zDi-?4);_0tbQk\, without the A prefix.

I'm not sure I'm expecting the right result, but I observed a lot of outputs beginning with the first character of my encoding (A).

Using SHA1, the result seems to be OK, but I'm suspecting the same issue appears with MD5 and SHA512.

Support Unix (OSX), Linux line endings

Hello I see the following error when trying to use jsHashes on Mac OSX:::

$ hashes md5-b64 hello
env: node\r: No such file or directory

This is because you are using windows line endings. I changed the line endings to Unix line endings and it worked. I am not sure which line endings will support all platforms.. hence no pull request. Thanks

PhantomJS

It seems so that it doesn't work in PhantomJS, it always returns the same hash for different outpusts (tested with MD5 and SHA1), works as expected in Chrome and Firefox

b64 padding .... bug/typpo ?

Digging on code, I found that.. and it seems strange
b64pad = (options && typeof options.pad === 'string') ? options.pda : '=', // base-64 pad character. Defaults to '=' for strict RFC compliance

Shouldn't options.pda be options.pad ?

If that's the case, i suspect same bug/typpo will repeat fro other Hash classes

Thousands of warnings in JSHint

I had problems running the minified version of jsHashes, so I ran the unminified version through CodeKit. JSHint reports over a thousands warnings on this file. Just thought I'd mention it :-P

Server installation instructions wrong

npm install jshashes results in the following server directory structure under express:

node_modules/jshashes/server/lib

your use instructions suggest using:

var Hashes = require('./lib/hashes');

This throws a cannot find module error

Bower having a wrong git endpoint

If I try to define in my component.json the dependency on jshashes as in the following:

{
    ...
    "jshashes": "master"
    ...
}

I get the following error:

bower jshashes#master                   ECMDERR Failed to execute "git ls-remote --tags --heads git://github.com/h2non/jsHashes.git", exit code of #128

It looks to me that the jshashes endpoint on bower is wrong and it should be:

git://github.com/h2non/jshashes.git

With the lowercase 'h'. To prove this I tried to define the dependency in this way:

{
    ...
    "jshashes": "git://github.com/h2non/jshashes.git#master"
    ...
}

And it worked fine. Is it possible to fix the definition on bower?

Thank you!

TypeScript type declaration file

If you want I can write a TypeScript type declaration file for this package so that TS developers can utilise the type-checking feature of the language as they use this package. Let me know if you are interested.

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.