GithubHelp home page GithubHelp logo

pvorb / node-md5 Goto Github PK

View Code? Open in Web Editor NEW
896.0 11.0 187.0 157 KB

a JavaScript function for hashing messages with MD5

Home Page: https://www.npmjs.com/package/md5

License: BSD 3-Clause "New" or "Revised" License

JavaScript 100.00%

node-md5's Introduction

MD5

build status info badge

a JavaScript function for hashing messages with MD5.

node-md5 is being sponsored by the following tool; please help to support us by taking a look and signing up to a free trial
GitAds

Installation

You can use this package on the server side as well as the client side.

npm install md5

API

md5(message)
  • message -- String, Buffer, Array or Uint8Array
  • returns String

Usage

const md5 = require('md5');

console.log(md5('message'));

This will print the following

78e731027d8fd50ed642340b7c9a63b3

It supports buffers, too

const fs = require('fs');
const md5 = require('md5');

fs.readFile('example.txt', function(err, buf) {
  console.log(md5(buf));
});

Versions

Before version 2.0.0 there were two packages called md5 on npm, one lowercase, one uppercase (the one you're looking at). As of version 2.0.0, all new versions of this module will go to lowercase md5 on npm. To use the correct version, users of this module will have to change their code from require('MD5') to require('md5') if they want to use versions >= 2.0.0.

Bugs and Issues

If you encounter any bugs or issues, feel free to open an issue at github.

Credits

This package is based on the work of Jeff Mott, who did a pure JS implementation of the MD5 algorithm that was published by Ronald L. Rivest in 1991. I needed a npm package of the algorithm, so I used Jeff’s implementation for this package. The original implementation can be found in the CryptoJS project.

License

Copyright © 2011-2015, Paul Vorbach.
Copyright © 2009, Jeff Mott.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.
* Neither the name Crypto-JS nor the names of its contributors may be used to
  endorse or promote products derived from this software without specific prior
  written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

node-md5's People

Contributors

caub avatar dependabot[bot] avatar deveshb15 avatar hipstersmoothie avatar keyle avatar macbre avatar mattdesl avatar pgilad avatar pvorb avatar salba avatar shakefu avatar shinnn avatar stevejhiggs avatar teramotodaiki avatar tyfkda 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

node-md5's Issues

Incorrect result for ArrayBuffer

Hi! Thanks for the great module! It's worked well for me, but I get the incorrect result for ArrayBuffer input, even if I wrap it in a Uint8Array. For example, and comparing to the js-md5 module:

> jsMd5 = require('js-md5')
> md5 = require('md5')

> buffer = new ArrayBuffer(9)
ArrayBuffer { byteLength: 9 }

> x = new Uint8Array(buffer)
Uint8Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

> jsMd5(buffer)
'3f2829b2ffe8434d67f98a2a98968652'
> jsMd5(x)
'3f2829b2ffe8434d67f98a2a98968652'

> md5(buffer)
'441018525208457705bf09a8ee3c1093'
> md5(x)
'f3c8bdb6b9df478f227af2ce61c8a5a1'

Checking the hash of the bytes directly via https://cryptii.com/pipes/md5-hash confirms the js-md5 result :

Screen Shot 2019-03-14 at 10 24 12 AM

See also: #42

inconsistent encoding for string message.

on the module.exports, I'm passing the options.asString=true and it returns the bin.bytesToString() - works exactly as I expected.

I add some other strings to the result - example: md5(returnedBinString + additionalMessage).
now md5 uses utf8.stringToBytes(message) - so that i'm not getting the result i'm expecting.

seems to me that the function in module.exports with options.asString=true is not using the same encoding as the md5(message) for strings.

for my use, I changed utf8.stringToBytes(message) to bin.stringToBytes(message) and everything works exactly as I expected.

Thanks.

Same hash for integer

Hi

I try to generate random hash as

var md5 = require('MD5');
var dt = (new Date).getTime();
var hash = md5( Math.floor((Math.random() * 100000) + 1) +  dt);
//hash = d41d8cd98f00b204e9800998ecf8427e[always]

But it shows the same hash even the dt and random numbers are different.

i solve this by converting the random integer to string by appending toString():

var dt = (new Date).getTime();
var hash = md5( (Math.floor((Math.random() * 100000) + 1) +  dt).toString());

If an Array of non-integers is mistakenly passed in, do not silently hash [0]

So in https://github.com/pvorb/node-md5/blob/master/md5.js#L17 we assume that any Array passed is a byte array. But it's likely to be a common developer mistake to accidentally pass in an Array of non-integers, say md5(someListOfStrings), in which case crypt.bytesToWords(message) returns [0], and md5 returns the identical hash '93b885adfe0da089cdf634904fd59f71'. This is undefined and unintended behavior that may be causing unnecessary collisions in the wild.

We should either add some sort of check for the type of the first entry, or clarify this in the documentation.

string result has number format

I have this string:
[deleted]

After md5, result is 777679371564033e5581379375814680. Event after I convert it to string using .toString. It always returns Infinity.

Error 403

I am getting an error 403 for while installing mp5 stating the security policy for my device(localhost) is forbidding my access to the package or one on its dependencies.

I could be wrong but this whole package could be 5 lines of code...

I was encountering a bug where I was attempting to md5 a file that was about 45mb with this module and I was getting this error:

FATAL ERROR: invalid table size Allocation failed - process out of memory

I replaced this module with this and now it works fine:

module.exports = function md5(input) {
    var alg = require('crypto').createHash('md5')
    alg.update(input)
    return alg.digest('hex');
}

The file I was attempting to hash was this file:
https://github.com/atom/electron/releases/download/v0.30.4/electron-v0.30.4-win32-x64.zip

Passing url object gives unexpected results

If you pass a url you get an unexpected result, including the same hash for different urls.

I suspect that the object is not converted to a string before a hash is calculated.

This may be by design, but it caught me out.

const md5 = require('md5');
const {URL} = require('url');

const myUrl = new URL("http://example.com/");
const oneUrl = new URL("http://example.com/body.html");
const twoUrl = new URL("http://example.com/menu.html");

console.log("No conversion:", md5(myUrl));
console.log("String conversion:", md5(myUrl.toString()));
console.log("Built-in:", md5(myUrl.href));
console.log("myUrl:", myUrl);
console.log("One:", md5(oneUrl));
console.log("Two:", md5(twoUrl));

/* Output

No conversion: 0e6bce6899fae841f79024afbdf7db1d
String conversion: a6bf1757fff057f266b697df9cf176fd
Built-in: a6bf1757fff057f266b697df9cf176fd
myUrl: URL {
  href: 'http://example.com/',
  origin: 'http://example.com',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'example.com',
  hostname: 'example.com',
  port: '',
  pathname: '/',
  search: '',
  searchParams: URLSearchParams {},
  hash: '' }
One: 1c9e99e48a495fe81d388fdb4900e59f
Two: 1c9e99e48a495fe81d388fdb4900e59f

*/

A little question

There is a really native way to calculate md5 hash in nodejs:

crypto.createHash('md5').update(string).digest("hex");

So what is your module for?

v2.2.0 changes behaviour and should therefore bump the major version number

I noticed that you changed the behaviour of the md5 function with regards to how it handles input parameters. This is potentially a breaking change for some developers and should be released as a major release and not a minor release.

v2.1.0 would return undefined when it was called with undefined. v2.2.0 throws TypeError: Cannot read property 'constructor' of undefined.

Apart from that, it looks like there is an issue with the following line: https://github.com/pvorb/node-md5/blob/master/md5.js#L151

The comparison does a === check against 'undefined' which is considered a String. Not sure if this the expected behaviour.

Proper usage?

Hey!

In the documentation says:

var md5 = require('MD5');

console.log(md5("message"));

But looking in the source code the proper usage seems to be md5.digest_s("message") instead md5("message").

Cheers

error when deal big file

when I use this package to md5 a buffer of a 400+MB file, the error comes and says:
FATAL ERROR: invalid table size Allocation failed - process out of memory

Proposal: use `is-buffer` module

This module could use is-buffer to check if the input object is a node Buffer, which will not cause the Buffer polyfill to be added during browserification.

The filesize differences:
Before PR: 25kb
After PR: 6kb

browserify md5.js | uglifyjs -cm | wc -c

Thanks for this module! I'm using it here: marvel-comics-api. 😄 🤘

How do you output the 16 length MD5 values?

Thanks for making such a great tool for md5, I have a question requiring a leave
How do you output the 16 length MD5 values?
console.log('md5', md5('test'), md5('test').length )
The result is:
md5 098f6bcd4621d373cade4e832627b4f6 32

I need to need a configuration that can support generating 16 length md5 values like the following result

String test
md5('test',{length: 16, lower: true })
16 length lowercase 4621d373cade4e83

md5('test',{length: 16, lower: false })
16 Length Capital 4621D373CADE4E83

md5('test',{length: 32, lower: true })
32 length lowercase 098f6bcd4621d373cade4e832627b4f6

md5('test',{length: 32, lower: false })
32 Length Capital 098F6BCD4621D373CADE4E832627B4F6

Error: Illegal argument undefined at module.exports

app.post("/login",function(req,res){
const username= req.body.username;
const password= md5(req.body.passowrd);

User.findOne({email:username},function(err,foundUser){
console.log(foundUser);
if(err){
console.log(passowrd);
console.log(err);
}
else{
if(foundUser){
if(foundUser.passowrd===password){
res.render("secrets");
}
}
}
});
});

URIError: URI malformed error

This code:

const md5 = require('md5');
const fourmis = 'foumis 🐜';
const fourmis2 = fourmis.substr(0, 8);
md5(fourmis2);

results in this error:

/mnt/d/Web/www/joplin/CliClient/node_modules/charenc/charenc.js:6
      return charenc.bin.stringToBytes(unescape(encodeURIComponent(str)));
                                                ^

URIError: URI malformed
    at encodeURIComponent (<anonymous>)
    at Object.stringToBytes (/mnt/d/Web/www/joplin/CliClient/node_modules/charenc/charenc.js:6:49)
    at md5 (/mnt/d/Web/www/joplin/CliClient/node_modules/md5/md5.js:14:24)
    at module.exports (/mnt/d/Web/www/joplin/CliClient/node_modules/md5/md5.js:154:42)

It is correct that the string is an invalid UTF-8 string however the MD5 function should probably handle this better. Especially when you are processing user input, this kind of invalid string can happen, but there's still a valid MD5 for it (which should work in terms of bytes and shouldn't have to deal with string encoding like UTF-8, etc.).

In my own code I've "fixed" it by calling md5(escape(string)), which is good enough for my use case, but I guess that wouldn't be a valid solution for the package.

Malformed URI

When I do this, I get a malformed URI exception.

  request( "http://news.bbcimg.co.uk/media/images/80408000/jpg/_80408441_022059218.jpg", function ( err, response, body ) {
    console.log( md5( body ) )
  })

hashed value coming differntly

hello..
i have a departmentid=5
i have to pass hashed departmentid when calling API.
for that i am using npm i md5
when i hardcoded value =5 for departmentId,
md5=require('md5') ,
console.log(md5('5')); i am getting correct hashed value
but when i give console.log(md5('departmentId')); getting differentvalue

API should be described in README

You write:

var md5 = require('MD5');
console.log(md5('message'));

But it should be

var md5 = require('MD5');
console.log(md5.digest_s('message'));
console.log(md5.digest([1,2,3]));

Different results between int and String

If I call md5 with an integer parameter it return a different value from md5 called with a string parameter.
e.g.
md5(1003) = 64e0407ffc70c04a366526a7065cbd05
md5('1003') = aa68c75c4a77c87f97fb686b2f068676.

Is it a normal behavior?

When using MD5 to encrypt numbers, the results are inconsistent

When I encrypt 100 with MD5, the result is as follows:

I/ReactNativeJS: .md5(100)===>', '30a771fb83c2f5000a74d41689f19c76'

I found in the source code, the number will be converted into a string, as follows

md5 = function (message, options) {

else if (isBuffer(message))

**else if (! Array.isArray (message) && message.constructor !== Uint8Array)

message = message.toString ();**

// else, assume byte array already

I spent three days trying, but I still couldn't find the same method as the above results in Java. I converted the number into a byte array in Java code, and then put it into the MD5 encryption provided by Apache. The returned result is the same as the result of encrypting the string "100" in this library, but I can't get the numerical result

md5 of blob

Possibly similar to #44, whenever I hash any blob, I always get 0b867e53c1d233ce9fe49d54549a2323 regardless of the contents of the blob. Probably I'm using it incorrectly. I'm probably not the only one. Searching for this hash on "all Github" we see it popping up in many places, such as auth0-extensions/auth0-account-link-extension#52 (comment)

Testing undefined message on library call

Hi,

With the update to version 2.2.0 we had a new error being thrown without understanding the issue.

Turns out we were sending an undefined message in our call
md5(undefined)

But the first test in the library
if (message === 'undefined' || message === null) throw new Error('Illegal argument ' + message);
is not properly catching the error as message === 'undefined' won't actually catch undefined variables.

A quick fix would be message === undefined or typeof message === 'undefined' or anything of your convenience.

Thank you for your work,

Update Document

When I use MD5 module , md5 becomes an object not a function.So I should type :

var md5 = require("MD5");

md5.digest_s('my string');

But the document says : md5('my_string')

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.