DebugPointer
Published on

Convert SHA256 string to base64 in JavaScript

Convert SHA256 string to base64 in JavaScript

As we've seen in earlier posts, you can create an SHA256 hash of a string and generate a hash in string type.

This implementation is for JavaScript on the frontend (Javascript, React.js, Vue.js etc.,), we implement the same in the backend using the default crypto module for nodejs.

In the code below, we are going to create an SHA256 hash using CryptoJS and then we use the btoa() method encodes a string in base-64. The btoa() method uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string in base-64.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SHA256</title>
  </head>
  <body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/sha256.js"></script>
    <script>
      let digest = "password";
      let hash = CryptoJS.SHA256(digest);
      hash = hash.toString(CryptoJS.enc.Base64);
      console.log(btoa(hash))
    </script>
  </body>
</html>

The output of the above code will be a base64 string-

NWU4ODQ4OThkYTI4MDQ3MTUxZDBlNTZmOGRjNjI5Mjc3MzYwM2QwZDZhYWJiZGQ2MmExMWVmNzIxZDE1NDJkOA

I'm glad that you found this article to create a base64 string out of SHA-256 hash useful. Happy Coding.