开发者

hash in JS == hash in PHP

I need to make a hash with JS and PHP but I need them to both work out to be the same hash. I am just wondering what the best idea would be to go about it. it needs to be secure, but its not hashing sensitive data so doesn't need a h开发者_如何学JAVAuge amount of security around it.

could anyone give me some examples

Thank you.


You could use MD5: the php and the JS solution should work out to be the same given the same string input. http://pajhome.org.uk/crypt/md5/ has a list of hash implementations in javascript, and PHP implementations of md5 are documented here, and both have examples at hand.

You'll need to be careful that you use the exact same input to both functions, but otherwise it shouldn't be too painful.


Well don't forget that javascript is inherently insecure because it is client side, but if you're hashing for communication with say ajax, or you don't want to spend the money on a ssl certificate, then this could be the way to go.

The most common hashing algorithms are md5 and sha256. Now, because these are algorithms they don't need to be coded into the language (as they are in php), but can written with the language. Some very smart people have already done the hard work for you, and now you just need to get their source.

MD5: http://www.webtoolkit.info/javascript-md5.html
SHA256: http://www.bichlmeier.info/sha256.html


A more modern approach

In PHP, use:

$hash = hash('sha256', "here_is_my_input_string");

Then in JavaScript you can use the Web Crypto API:

function hashAsync(algo, str) {
  return crypto.subtle.digest(algo, new TextEncoder("utf-8").encode(str)).then(buf => {
    return Array.prototype.map.call(new Uint8Array(buf), x=>(('00'+x.toString(16)).slice(-2))).join('');
  });
}

hashAsync("SHA-256", "here_is_my_input_string").then(outputHash => console.log(outputHash));
// prints: 4bb047046382f9c2aeb32ae6d2e43439f05d11bd74658f1d160755ff48114364 which also matches 3rd party site: https://emn178.github.io/online-tools/sha256.html

Thanks to https://stackoverflow.com/a/55926440/470749

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜