Aliaksandr Yedomski
Aliaksandr Yedomski

Reputation: 48

NodeJS md5 'bytestring' like PHP md5(str, true)

I've faced with following issue: i try to convert some string str to md5 bytestring hash. In PHP we can use md5(str, true), but in JS (nodejs express) i can't find some way to receive the same result. I've included npm module js-md5, but arrayBuffer method of this module returns another result (differes from PHP md5(str, true)).

Could somebody help me, please.

Thanks

Upvotes: 2

Views: 1172

Answers (3)

Mridul
Mridul

Reputation: 266

var md5 = require('md5');
console.log(md5('text'))

Upvotes: 1

Iso
Iso

Reputation: 3238

Short answer:

const crypto = require('crypto');
const buffer = crypto.createHash('md5').update(str).digest();

Long answer: you need to use NodeJS’ default crypto module (no need for a dependency here), which contains utility function and classes. It is able to create hashes (for instance MD5 or SHA-1 hashes) for you using synchronous or asynchronous methods. A short utility function named crypto.createHash(algorithm) is useful to create a hash with minimal coding. As the docs specifies:

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list-message-digest-algorithms will display the available digest algorithms.

Now, this createHash function returns a Hash object, which can be used with a stream (you can feed it a file, HTTP request, etc.) or a string, as you asked. If you want to use a string, use hash.update(string) to hash it. This method returns the hash itself, so you can chain it with .digest(encoding) to generate a string (if encoding is set) or a Buffer (if it’s not). Since you asked for bytes, I believe a Buffer is what you want (Buffers are Uint8Array instances).

Upvotes: 0

Aethyn
Aethyn

Reputation: 705

Use CryptoJS module : NPM link here

And do something like :

// Requires
var crypto = require('crypto');

// Constructor
function Crypto() {
    this.hash;
}

// Hash method
Crypto.prototype.encode = function(data) {
    this.hash = crypto.createHash('md5').update(data);
    var result = this.hash.digest('hex');
    return result;
};

// Comparison method (return true if === else false)
Crypto.prototype.equals = function(data, model) {
    var bool = false;
    var data = data.toUpperCase();
    var model = String(model).toUpperCase();
    if (data == model){
        bool = true;
    } else {
        bool = false;
    }
    return bool;
};

// Exports
module.exports = Crypto;

Then instantiate this "tool" object in your code and use methods.
Easy as pie, and the same thing can be done with anothers encryption methods like AES, SHA256, etc.
About the raw_output option (binary answer, padded on 16 bits) you can easily convert the returned var in binary format with a simple function, see this SO post to know how. Have fun.

Upvotes: 0

Related Questions