• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

JavaScript HMAC SHA256 Hash Example using Forge & CryptoJS

May 14, 2019 by javainterviewpoint Leave a Comment

Hash based Message Authentication Code (HMAC) is a mechanism for calculating a Message Authentication Code (MAC) involving hash function in combination with a Secret key. HMAC can be used to verify both the data integrity and the authenticity of the message. In this article, we will learn about JavaScript HMAC SHA256 Hash using Forge and CryptoJS.

HMACs are almost similar to Digital Signatures. They both use cryptographic keys and employ hash functions. The main difference is that Digital Signatures use asymmetric keys, while HMACs use symmetric keys.

HMAC can be used to determine whether a message sent over an insecure channel has been tampered or not, with the condition that the sender and receiver share a secret key. The sender calculate the hash value for the data and sends both the original data and hash value as a single message.On the receiving end, the receiver recalculates the hash value of message which is received and validate whether the HMAC transmitted matches the HMAC which is received.

Any injection or modification to the original data will result in error, as the secret key should be known to reproduce the exact hash value and hence, if the original and computed hash values match, then the message is authentic.

Let’s dig into the code

JavaScript HMAC SHA256 Hash Example Using Forge

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/forge/0.8.2/forge.all.min.js"></script>

    
    <script type="text/Javascript">
        
        function generateHash()
	{
            var plainText = document.getElementById('plainText').value;

            var secretKey = document.getElementById('secretKey').value;

	    var hmac = forge.hmac.create();  
            hmac.start('sha256', secretKey);
            hmac.update(plainText);  
            var hashText = hmac.digest().toHex();  
            document.getElementById("hashText").innerHTML = hashText;
        }        
    </script>
</head>
<body>
    
    <h1>JavaScript HMAC SHA256 Hash Example Using Forge</h1>

    <br><strong>Enter the Sample Text : </strong><input id='plainText' type='text' />
    
    <br><br><strong>Enter the Secret Key   : </strong><input id='secretKey' type='text' />

    <br><br><strong>Hashed Text (HMAC SHA256)  : </strong><span id='hashText'></span>

    <br><br><button onclick="generateHash()">Calculate Hash</button>
</body>
</html>
  • In order to use Forge for HMAC SHA-256 Hashing, we need to add the dependencies jquery.min.js and forge.all.min.js
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/forge/0.8.2/forge.all.min.js”></script>
  • Get the data which needs to be hashed and the secret key from the user

<strong>Enter the Sample Text : </strong><input id=’plainText’ type=’text’ />

<strong>Enter the Secret Key : </strong><input id=’secretKey’ type=’text’ />

  • The generateHash() method performs the HMAC SHA256 hashing, this method will be called when the user clicks on the “Calculate Hash” button

<button onclick=“generateHash()”>Calculate Hash</button>

  • Now create the forge instance initialized for HMAC by calling the create() method
var hmac = forge.hmac.create();
  • Call the start() method passing Cryptographic Hash Algorithm which is sha256 in our case and the secret key.
hmac.start(‘sha256’, secretKey);
  • Pass the plainText which is received from the user to the update()
hmac.update(plainText);
  • The digest() method performs the actual hashing and returns the hashed version of the text passed to it.
var hashText = hmac.digest().toHex();
Output:
  • Copy the above code to the text editor and save it with a html extension and open the file in the browser
  • Enter the sample text and secret key and click on the “Calculate Hash” button to calculate the hash of the text entered.

JavaScript HMAC SHA256 Hash Example

JavaScript HMAC SHA256 Hash Example Using CryptoJS

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/crypto-js.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/hmac-sha256.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/enc-base64.min.js"></script>
    
    <script type="text/Javascript">
        
        function generateHash()
		{
        	var plainText = document.getElementById('plainText').value;
            var secretKey = document.getElementById('secretKey').value;
            
			var hashText = CryptoJS.HmacSHA256(plainText, secretKey);   

            //document.getElementById("hashText").innerHTML = CryptoJS.enc.Base64.stringify(hashText);
            document.getElementById("hashText").innerHTML = hashText;
        }        
    </script>
</head>
<body>
    
    <h1>JavaScript HMAC SHA256 Hash Example Using CryptoJS</h1>

	<br><strong>Enter the Sample Text : </strong><input id='plainText' type='text' />

    <br><br><strong>Enter the Secret Key   : </strong><input id='secretKey' type='text' />

	<br><br><strong>Hashed Text (HMAC SHA256)  : </strong><span id='hashText'></span>

	<br><br><button onclick="generateHash()">Calculate Hash</button>
</body>
</html>
  • In order to use CryptoJS for HMAC SHA-256 Hashing, we will have to add the dependencies crypto-js.min.js, hmac-sha256.min.js and enc-base64.min.js
<script src=”https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/crypto-js.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/hmac-sha256.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9/enc-base64.min.js”></script>
  • Get the data which needs to be hashed and the secret key from the user

<strong>Enter the Sample Text : </strong><input id=’plainText’ type=’text’ />

<strong>Enter the Secret Key : </strong><input id=’secretKey’ type=’text’ />

  • The generateHash() method will be called when the user clicks on “Calculate Hash” button

<button onclick=“generateHash()”>Calculate Hash</button>

  • Pass the plainText (entered by the user) and the secret key to the HmacSHA256(), to perform the hashing

function generateHash()
{
      var plainText = document.getElementById(‘plainText’).value;

      var secretKey = document.getElementById(‘secretKey’).value;

      var hashText = CryptoJS.HmacSHA256(plainText, secretKey);

     document.getElementById(“hashText”).innerHTML = hashText;
}

Other interesting articles which you may like …

  • JavaScript SHA256 Hash Example
  • ChaCha20 Poly1305 Encryption and Decryption
  • ChaCha20 Encryption and Decryption
  • RSA Encryption and Decryption
  • AES 256 Encryption and Decryption
  • AES 128 Encryption and Decryption
  • Java URL Encode and Decode Example
  • Java Salted Password Hashing
  • Google Tink Example – Google Cryptography
  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serialization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: JavaScript Tagged With: HMAC SHA256, HMAC SHA256 CryptoJS, HMAC SHA256 Forge, JavaScript HMAC SHA256, JavaScript HMAC SHA256 Hash

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·