As a JavaScript developer, I’m constantly working with various data encryption and encoding techniques to ensure the security and integrity of sensitive information. One such technique that often comes into play is converting SHA256 strings to base64. In this blog post, I’ll guide you through the process of performing this conversion in JavaScript. It’s a valuable skill to have in your coding toolbox, allowing you to work with hashed data in a more versatile and efficient manner. So, let’s dive in and explore how to convert SHA256 strings 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.
Converting SHA256 strings to base64 in JavaScript
This implementation is for JavaScript on the frontend (Javascript, React.js, Vue.js etc.,), we implement the same in the backend using the default cryptography module for nodejs.
In the code below, we are going to create an SHA256 hash using cryptographyJS
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/cryptography-js/4.1.1/core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cryptography-js/4.1.1/sha256.js"></script>
<script>
let digest = "password";
let hash = cryptographyJS.SHA256(digest);
hash = hash.toString(cryptographyJS.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. We’ve reached the end of our journey, where we’ve learned how to convert SHA256 strings to base64 in JavaScript. This newfound skill opens up a world of possibilities in terms of working with hashed data, enabling us to manipulate and transmit it more effectively. As a developer, it’s essential to be well-versed in encryption and encoding techniques, and this knowledge equips us with the tools to safeguard sensitive information. So go ahead, apply this technique in your projects, and elevate your data security to new heights. Happy coding!