JavaScript/HASH:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
小 文字替换 -“{{leftrightflex|”替换为“{{Double-columns|”
 
(未显示同一用户的1个中间版本)
第20行: 第20行:
=== 霍纳算法 ===
=== 霍纳算法 ===
实现一:
实现一:
{{leftrightflex|<syntaxhighlight lang="javascript">
{{Double-columns|<syntaxhighlight lang="javascript">
String.prototype.HASHCode = function(){
String.prototype.HASHCode = function(){
   let hash = 0;
   let hash = 0;
第34行: 第34行:


实现二:
实现二:
{{leftrightflex|<syntaxhighlight lang="javascript">
{{Double-columns|<syntaxhighlight lang="javascript">
String.prototype.HASHCode = function(){
String.prototype.HASHCode = function(){
   const MAX_VALUE = 0x7fffffff;
   const MAX_VALUE = 0x7fffffff;
第46行: 第46行:
}
}
console.log("Hello World!".HASHCode()); </syntaxhighlight>|{{consoleout|<pre>-969099747
console.log("Hello World!".HASHCode()); </syntaxhighlight>|{{consoleout|<pre>-969099747
</pre>}}}}
== SHA ==
{{Double-columns|<syntaxhighlight lang="javascript">
String.prototype.SHACode = async function(){
  const msgUint8 = new TextEncoder().encode(this)                     
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8)         
  const hashArray = Array.from(new Uint8Array(hashBuffer))                   
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
  return hashHex;
}
console.log(await "Hello World!".SHACode()); </syntaxhighlight>|{{consoleout|<pre>
7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069
</pre>}}}}
</pre>}}}}