hash in JS == hash in PHP

橙三吉。 提交于 2020-03-23 07:00:01

问题


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 huge amount of security around it.

could anyone give me some examples

Thank you.


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/6991401/hash-in-js-hash-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!