Created
December 18, 2020 21:58
-
-
Save cyril/5bfb29920a9ffdf5399b5bfdb7aa0eab to your computer and use it in GitHub Desktop.
Uses the SubtleCrypto interface of the Web Cryptography API to hash a message using SHA-1, SHA-256, SHA-512.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>Crypto SHA</title> | |
<meta charset="utf-8" /> | |
<meta content="width=device-width, initial-scale=1" name="viewport" /> | |
<script> | |
function SHA256() { | |
var str = document.getElementById('plainTextGCM').value; | |
var buffer = new TextEncoder('utf-8').encode(str); | |
return crypto.subtle.digest('SHA-256', buffer).then( | |
function (hash) { | |
document.getElementById('hashtext').value = hex(hash) | |
} | |
); | |
} | |
function SHA512() { | |
var str = document.getElementById('plainTextGCM').value; | |
var buffer = new TextEncoder('utf-8').encode(str); | |
return crypto.subtle.digest('SHA-512', buffer).then( | |
function (hash) { | |
document.getElementById('hashtext').value = hex(hash) | |
} | |
); | |
} | |
function SHA1() { | |
var str = document.getElementById('plainTextGCM').value; | |
var buffer = new TextEncoder('utf-8').encode(str); | |
return crypto.subtle.digest('SHA-1', buffer).then( | |
function (hash) { | |
document.getElementById('hashtext').value = hex(hash) | |
} | |
); | |
} | |
function hex(buffer) { | |
var hexCodes = []; | |
var view = new DataView(buffer); | |
for (var i = 0; i < view.byteLength; i += 4) { | |
// Using getUint32 reduces the number of iterations needed (we process 4 bytes each time) | |
var value = view.getUint32(i); | |
// toString(16) will give the hex representation of the number without padding | |
var stringValue = value.toString(16); | |
// We use concatenation and slice for padding | |
var padding = '00000000'; | |
var paddedValue = (padding + stringValue).slice(-padding.length); | |
hexCodes.push(paddedValue); | |
} | |
// Join all the hex strings into one | |
return hexCodes.join(''); | |
} | |
</script> | |
<style> | |
input { | |
font-family: "Courier New", Courier, monospace; | |
font-size: 2em; | |
width: 100%; | |
} | |
</style> | |
</head> | |
<body> | |
<p> | |
<label>Plain text: <input type="text" id="plainTextGCM" value="" /></label> | |
</p> | |
<ul> | |
<li><button type="button" onclick="SHA1()">SHA1</button></li> | |
<li><button type="button" onclick="SHA256()">SHA256</button></li> | |
<li><button type="button" onclick="SHA512()">SHA512</button></li> | |
</ul> | |
<p> | |
<label>Hashed text: <input type="text" id="hashtext" /></label> | |
</p> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment