Quiero registrar hashes de secuencias de comandos para implementar la política de seguridad de contenido. He podido generar el hash en python con el siguiente código:
import hashlib import base64 string=''' //<![CDATA[ var theForm = document.forms['ctl00']; if (!theForm) { theForm = document.ctl00; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> ''' # encode as UTF-8 string_UTF8 = string.encode('utf-8') # hash the message hash_string = hashlib.sha256(string_UTF8).digest() # base64 encode result = base64.b64encode(hash_string) print('sha256-' + result.decode('utf-8'))
¿Cómo puedo hacer esto con Javascript?
const string = ` //<![CDATA[ var theForm = document.forms['ctl00']; if (!theForm) { theForm = document.ctl00; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> ` async function hashFromString(string) { const hash = await crypto.subtle.digest("SHA-256", (new TextEncoder()).encode(string)) return "sha256-" + btoa(String.fromCharCode(...new Uint8Array(hash))) } hashFromString(string).then(console.log)
Editar: ahora me doy cuenta de que, si bien no se indica en su pregunta, es probable que esté usando Node.js, por lo que esta respuesta que usa las API del navegador puede ser menos útil.
Terminé usando este complemento de JQuery https://github.com/angeal185/jquery-hash El siguiente código obtiene la respuesta correcta:
<script> var s = "\n//<![CDATA[\nvar theForm = document.forms['ctl00'];\nif (!theForm) {\n theForm = document.ctl00;\n}\nfunction __doPostBack(eventTarget, eventArgument) {\n if (!theForm.onsubmit || (theForm.onsubmit() != false)) {\n theForm.__EVENTTARGET.value = eventTarget;\n theForm.__EVENTARGUMENT.value = eventArgument;\n theForm.submit();\n }\n}\n//]]>\n" $.hash(s, '256', 'base64',function(i){ console.log(i) }); </script>