pvorb/node-md5

How to convert md5 string in javascript to 128-bit array.

cmhsu-cs opened this issue · 1 comments

How would I go about doing this? Thank you in advance.

pvorb commented

md5 doesn't support this out-of-the-box, but you can easily convert the resulting hex string to an array of bits/booleans/bytes.

I'm not sure what you exactly mean by 128-bit array. Do you really want an array of 128 boolean/number values? A byte array of 16 bytes is a more common way to represent an MD5 hash. You can convert the result of md5() to a byte array using the following function:

function hexByteStringToByteArray(hexByteString) {
    var bytes = new Array(16); // this could also be a new Uint8array(16)
    for (var i = 0; i < hexByteString.length;) {
        var hexByte = hexByteString[i++] + hexByteString[i++];
        var byte = parseInt(hexByte, 16);
        bytes[i / 2 - 1] = byte;
    }
    return bytes;
}

Example:

var md5 = require('md5');
var hexHash = md5('example');
var bytes = hexByteStringToByteArray(hexHash);

Alternatively, you could do a conversion to booleans with the following function:

function hexByteStringToBooleanArray(hexByteString) {
    var booleans = [];
    for (var i = 0; i < hexByteString.length;) {
        var hexByte = hexByteString[i++] + hexByteString[i++];
        var byte = parseInt(hexByte, 16);
        for (var j = 7; j >= 0; j--) {
            var boolean = ((byte >> j) & 0x1) > 0;
            booleans.push(boolean);
        }
    }
    return booleans;
}

And this one is for bits (0 and 1 stored as 64 bit floating point numbers):

function hexByteStringToBitArray(hexByteString) {
    var bits = [];
    for (var i = 0; i < hexByteString.length;) {
        var hexByte = hexByteString[i++] + hexByteString[i++];
        var byte = parseInt(hexByte, 16);
        for (var j = 7; j >= 0; j--) {
            var bit = (byte >> j) & 0x1;
            bits.push(bit);
        }
    }
    return bits;
}

I hope this answer helps you.