Search code examples
javascripthtmldomhashcryptojs

Hashing element contents in-place with Crypto-js


I am trying to hash data using JavaScript. When I run the first code it will hash using document.write. Now I try the second code to hash by content id it didn't work. Can anyone explain why?

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js"></script>
<script>
    var hash = CryptoJS.SHA256("hello");
    document.write(hash.toString(CryptoJS.enc.Hex));
</script>

using this first method will work very fine 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

<script>
    var hash = CryptoJS.SHA256;
    var it = (hash.toString(CryptoJS.enc.Hex));
    document.getElementById('hashit').innerHTML = 'it';
</script>

<p id="hashit">Hello</p>

Solution

  • If you want to hash something in-place in an element then you need to read out the value/text, hash it and write the text back:

    var element = document.getElementById('hashit');
    var hash = CryptoJS.SHA256(element.innerHTML);
    element.innerHTML = hash.toString();
    

    Here is a runnable snippet which changes the value after 2 seconds.

    setTimeout(function(){
      var element = document.getElementById('hashit');
      var hash = CryptoJS.SHA256(element.innerHTML);
      element.innerHTML = hash.toString();
    }, 2000);
    <script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/sha256.js"></script>
    <p id="hashit">Hello</p>

    Keep in mind that JavaScript is not like PHP. You can't simply use variables in strings like this element.innerHTML = 'it';. You have to useelement.innerHTML = it;.