简体   繁体   English

普通Javascript中的字母数字哈希函数

[英]Alphanumeric hash function in plain Javascript

I am looking for a way to covert a given string into an alphanumeric hash. 我正在寻找一种将给定字符串转换为字母数字哈希的方法。 The code will be executed on the client-side and must be entirely in vanilla JS or jQuery at the most. 该代码将在客户端执行,并且最多必须完全在原始JS或jQuery中。

Is there, however, also a non-cryptographic hash, ie just a string of alphanumerics that does not require crypto and Promises ? 但是,是否还存在非加密哈希,即仅一串不需要cryptoPromises的字母数字? I need both, ie a cryptographic as well as a non-cryptographic hash. 我既需要加密哈希,也需要非加密哈希。

The second hash can be an ordinary string of alphanumerics, say 10 characters long. 第二个哈希可以是一个普通的字母数字字符串,长度为10个字符。 It should be recoverable, ie the same hash should be recreated always for a given string. 它应该是可恢复的,即应始终为给定的字符串重新创建相同的哈希。 It would be better if this second hash is not generated asynchronously (ie using Promises ). 如果第二个哈希值不是异步生成的(即使用Promises ),那会更好。 I intend to use it as a key for a boolean in window.localStorage (for many different strings). 我打算将其用作window.localStorageboolean的键(用于许多不同的字符串)。

Final answers: 最终答案:

Modern browsers provide cryptographic algorithms implementation via window.crypto object. 现代浏览器通过window.crypto对象提供密码算法实现。 You can look at what "modern" means in this case by this link (at the bottom). 您可以通过链接(在底部)查看“现代”在这种情况下的含义。 If you are fine with supported browsers list, then you can reach your goal for example like this: 如果您对受支持的浏览器列表满意,那么可以实现以下目标:

async function hash(target){
   var buffer = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(target));
   var chars = Array.prototype.map.call(new Uint8Array(buffer), ch => String.fromCharCode(ch)).join('');
   return btoa(chars);
};

It will hash your string (bytes of its utf-8 encoding) with SHA-256 and then convert result to base64. 它将使用SHA-256对您的字符串(其utf-8编码的字节)进行哈希处理,然后将结果转换为base64。

Note that if you don't need cryptographically strong hash (you didn't clarify the purpose) - then there might be better (faster) alternatives. 请注意,如果您不需要加密强度高的哈希(没有弄清目的),那么可能会有更好(更快)的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM