Generate a Hash from string in Javascript

前端 未结 22 1278
不知归路
不知归路 2020-11-22 03:34

I need to convert strings to some form of hash. Is this possible in JavaScript?

I\'m not utilizing a server-side language so I can\'t do it that way.

22条回答
  •  没有蜡笔的小新
    2020-11-22 04:15

    SubtleCrypto.digest

    I’m not utilizing a server-side language so I can’t do it that way.

    Are you sure you can’t do it that way?

    Did you forget you’re using Javascript, the language ever-evolving?

    Try SubtleCrypto. It supports SHA-1, SHA-128, SHA-256, and SHA-512 hash functions.


    async function hash(message/*: string */) {
    	const text_encoder = new TextEncoder;
    	const data = text_encoder.encode(message);
    	const message_digest = await window.crypto.subtle.digest("SHA-512", data);
    	return message_digest;
    } // -> ArrayBuffer
    
    function in_hex(data/*: ArrayBuffer */) {
    	const octets = new Uint8Array(data);
    	const hex = [].map.call(octets, octet => octet.toString(16).padStart(2, "0")).join("");
    	return hex;
    } // -> string
    
    (async function demo() {
    	console.log(in_hex(await hash("Thanks for the magic.")));
    })();

提交回复
热议问题