rsk82
rsk82

Reputation: 29387

is there any builtin javascript string hash function in newest browsers?

Everytime a new versions of browsers show up I hear about new stuff being added, like say webGL and other technologies that no one really knows if they catch up.

But I wonder if someone ever thought about such basic stuff in JS like hashing functions (MD5,SHA1 and the like).

By newest browsers I mean today's development versions too like Opera 12, Chrome 17 or Firefox 10.

Looking now for solution I found this comment on another thread here: https://stackoverflow.com/questions/7204097/short-hashing-function-for-javascript (Do you know that javascript objects already are hashtables ?). So what are these 'hashtables' ? Does it mean that I can make any string into a hash, but not an established one like md5 or sha1 but some JS build in specific ?

basically what I need to do is:

var txt="Hello world!";
var hash = txt.toSha1();

Upvotes: 51

Views: 52661

Answers (4)

Dipesh KC
Dipesh KC

Reputation: 3297

Note: This answer was written in 2014 when the Web Cryptography API was not available. Do not use this in the context where cryptographic security is needed. This may be useful when you need a simple reversible encryption with "builtin" support.

When I need simple client side hashing without external libraries I use the browsers' built in atob() and btoa() functions.

window.btoa() creates a base-64 encoded ASCII string from a "string" of binary data.

function utf8_to_b64( str ) {
    return window.btoa(encodeURIComponent( escape( str )));
}

The window.atob() function decodes a string of data which has been encoded using base-64 encoding.

function b64_to_utf8( str ) {
    return unescape(decodeURIComponent(window.atob( str )));
}

http://caniuse.com/#search=btoa and http://caniuse.com/#search=atob shows it is hugely supported by the modern browsers

Example taken from https://developer.mozilla.org/en-US/docs/Web/API/window.btoa

Upvotes: -8

Yoz
Yoz

Reputation: 990

async function sha256(source) {
    const sourceBytes = new TextEncoder().encode(source);
    const digest = await crypto.subtle.digest("SHA-256", sourceBytes);
    const resultBytes = [...new Uint8Array(digest)];
    return resultBytes.map(x => x.toString(16).padStart(2, '0')).join("");
}

Upvotes: 8

Sam Bull
Sam Bull

Reputation: 3229

For anybody still looking for this information. There is a WebCrypto API which appears to have been finalised at the beginning of 2017.

To use it in a browser, you can find it at window.crypto.subtle which contains methods for encryption, digests etc. Documentation on the available functions here.

Upvotes: 56

Greg Guida
Greg Guida

Reputation: 7512

Paul Johnston has implemented the following algorithms in javascript

MD5, RIPEMD-160, SHA-1, SHA-256 and sha-512

You can find the source code and some examples here: http://pajhome.org.uk/crypt/md5/

I hope this is what you were looking for.

Upvotes: 6

Related Questions