How to correctly invoke and use js-hs1?

Asked

Viewed 775 times

0

I need to encrypt a phrase with SHA1, but as I get nothing back I believe I’m not doing it right! Someone knows how to do it right?

I have the following excerpt from a script, where I have a variable that stores the phrase and then the function that would supposedly return me a SHA1 hash:

const sha1 = require ('js-sha1')

var frase = "when in doubt, leave it out. joshua bloch"
var cryptoFrase = crypto(frase)
alert(cryptoFrase)

function crypto(txt){
    sha1 (resp)
    var hash = sha1.create ()
    hash.update (resp)
    hash.hex ()

    return hash
}

1 answer

1


Friend, by your question we can not be sure if you want to calculate the hash on the front (browser) or back (nodejs), but follows below the two ways:

By Navigator

You can use the Subtlecrypto.Digest() which already comes embedded in the browsers.
Below is an example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <input type="text" name="texto1" id="texto1">
    <br>
    <input type="button" value="Calcular Hash" onclick="criarHash()">
    <br>
    <textarea name="hashtexto" id="hash" cols="30" rows="10"></textarea>
    
    
    <script>
        async function criarHash() {
            const texto = document.getElementById('texto1').value;
            const buffer = new TextEncoder( 'utf-8' ).encode( texto );
            const digest = await crypto.subtle.digest('SHA-1', buffer);
            const hash = Array.from(new Uint8Array(digest)).map( x => x.toString(16).padStart(2,'0') ).join('');
            document.getElementById('hash').value = hash;    
        }
    </script>
</body>
</html>

Pelo Nodejs

If you are trying to calculate the hash from the back end first you need to install the library js-sha1:

npm i js-sha1

Then your code can be done this way (as indicated on the library’s own page):

const sha1 = require ('js-sha1');

sha1('teste');
var hash = sha1.create();
hash.update('teste');
hash.hex();
  • @Tadeuagostini as so?

  • Vlw Murililo, I think I’m getting there. :obj.resumo_criptografico = criarHash(txt)&#xA; async function criarHash(txt) {&#xA; const buffer = new TextEncoder( 'utf-8' ).encode( txt )&#xA; const digest = await crypto.subtle.digest('SHA-1', buffer)&#xA; const hash = Array.from(new Uint8Array(digest)).map( x => x.toString(16).padStart(2,'0') ).join('')&#xA; alert(hash)&#xA; return hash&#xA;}&#xA;alert(obj.resumo_criptografico) For my goal is to add the hash to my object so that when I print it shows [Object Promise]

  • @Tadeuagostini to do what you’re wanting has to treat the answer as a Promise, so remove your code obj.resumo_criptografico = criarHash(txt) and add the following instead criarHash("teste").then((result)=>{&#xA; obj.resumo_criptografico = result;&#xA; alert(obj.resumo_criptografico);&#xA; &#xA; });

  • @Tadeuagostini just one more thing, if the answer helped you with your question of how to calculate the hash please consider marking it as correct to help others with the same doubt as you

  • Murilo this last snippet of code that you suggested, it printa correct only at the time it is running but when I use obj.resume_cryptographic later it returns me empty, like this?

  • @Tadeuagostini think that you are not understanding the concept of Promise, the execution of it is asynchronous, ie, if you are in a method that is synchronous he will not wait for the return of the Promise, he will call the Promise (which will run 'parallel') and will continue the execution of the rest of the code even if the file has not returned yet. That’s why when you try to do something with the obj.resumo_criptografico right after I call criarHash He’s empty, you must work with him inside the then.

  • Murilo really wasn’t understanding, but that last comment was very enlightening! Thanks again, kisses. =*

  • But one more thing Murilo this hash calculation returns me a different value than is expected from the return of an example SHA1: expected = cf726026091c2eebfbedff1c4cc0b98afee6219e return= 3217accf836703467f2af0f195edc3d0fcb5a9dd pro that this?

  • @Tadeuagostini, are you sure that this Hash you are waiting for is SHA1? What text is generating this hash? I tested on these sites the text "test" and this giving the same hash as in my example here and here, this second is even from the js-sha1 library you wanted to use.

  • It’s true I had a disagreement that I didn’t realize

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.