Generate HMAC hash using C# within a Javascript environment

Below is a C# function that I have;

private string GetEncyptionData(string encryptionKey)
    {
        string hashString = string.Format("{{timestamp:{0},client_id:{1}}}", Timestamp, ClientId);
        HMAC hmac = HMAC.Create();
        hmac.Key = Guid.Parse(encryptionKey).ToByteArray();
        byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(hashString));
        string encData = Convert.ToBase64String(hash);
        return encData;
    }

I am attempting to convert this code into Javascript. In my search for solutions, I stumbled upon this library as a useful tool.

Here is the code I currently have in Javascript;

 <script>
            var timestamp = 1424890904;
            var client_id = "496ADAA8-36D0-4B65-A9EF-EE4E3659910D";
            var EncryptionKey = "E69B1B7D-8DFD-4DEA-824A-8D43B42BECC5";

            var message = "{timestamp:{0},client_id:{1}}".replace("{0}", timestamp).replace("{1}", client_id);

            var hash = CryptoJS.HmacSHA1(message, EncryptionKey);
            var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);       

             alert(hashInBase64);
        </script>

However, the above code does not produce the same output as the C# code. How can I achieve parity between the two codes in Javascript?

Answer №1

The root of your problem lies with the key you are using. When working with C#, a 16-byte array is typically passed as the key. However, in CryptoJS, a string is used as the input for the key, which CryptoJS interprets as a passphrase. This leads to the generation of a key that differs from what you intended.

UPDATE: To obtain the correct key in javascript, follow these steps:

If you convert your 16-byte key to Base64, you can then use it in JavaScript as demonstrated below. This will produce a WordArray that serves as the key for generating your hash.

var keyBase64 = "eFY0EiMBZ0UBI0VniRI0Vg==";
var key = CryptoJS.enc.Base64.parse(keyBase64);
var hash = CryptoJS.HmacSHA1("Hello", key);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash); 
console.log(hashInBase64);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to determine if the validityMessage is currently being displayed on a DOM element using reportValidity()?

When reportValidity() is called on an invalid field, the validation message is displayed in a manner that varies depending on the browser. However, if reportValidity() is called again, the validation message disappears on Safari but not on Firefox. Contin ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

Three Js is unable to identify OBJLoader

Seeking assistance to resolve an error message while attempting to load a 3D Model in Three.js. Unable to find any information online about this issue. Can anyone provide guidance? I have confirmed that the mtl and obj libraries are being called in the co ...

Exploring the Depths: Navigating and Showing Complexly Nested Objects/JSON using React

After making an API request and processing the data using groupBy and sortBy, I store it in the state. useEffect(() => { const fetchTeamData = async () => { const result = await axios( `https://example.com/api-call`, ...

How to Trigger a Callback Function in Angular Template?

Within my directive for tables, I have the ability to output values based on specific properties. For example: <tr ng-repeat="item in table.data"> <td ng-repeat="column in table.columns"> <i ng-if="column.type === 'icon&apo ...

Learn the ins and outs of Ember.js with our comprehensive tutorial and guide. Discover solutions to common issues such as DS

Learning Ember has been a challenging experience for me. The guide I am using seems to be lacking important information that I need. I keep encountering two specific errors: Uncaught Error: Ember.State has been moved into a plugin: https://github.com/e ...

What is the best way to set up the SQLite database upon deploying/installing the application?

Just starting out with c#/.NET and working on developing an application using SQlite database and entity framework. Everything is running smoothly during testing phase. Currently, I am setting the file path for the .db file as shown below: var path = AppDo ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

Timing problem in AngularJS service when sharing data with components on a single page

I am encountering an issue while using multiple components on a composite page and trying to reference data from a common service. The main problem arises when I attempt to create the object in the service within the first component and then access it in t ...

The curly braces in AngularJS are failing to display the values on the HTML page

After trying various articles and solutions to different questions, I am still unable to resolve my issue. I am working on a blank ionic project and it is running smoothly in my browser using ionic serve without any errors. However, instead of displaying ...

Creating a number of arrays based on the row of a .CSV file can be accomplished in Angular by utilizing the

Implementing an Angular template to read .CSV files and generate a table involves creating two separate files: one for the header and another for the table content. For the header CSV file: header.csv https://i.stack.imgur.com/ojMo6.png For the table da ...

Enhance your Next.js (React) Component by implementing a feature that filters table results without causing unnecessary re

I am currently working on a Next.js client component that displays a data table with a search bar for filtering. The main issue I'm facing is that when I type in the search bar, the entire component re-renders, causing the search to lose focus and int ...

Changing dates in JavaScript / TypeScript can result in inaccurate dates being displayed after adding days

Recently, I encountered an issue with a simple code snippet that seems to produce inconsistent results. Take a look at the function below: addDays(date: Date, days: number): Date { console.log('adding ' + days + ' days'); con ...

What is the process for modifying a Date type value in JavaScript?

I'm looking to create a graph that illustrates the sun's altitude throughout the day, resembling a sine curve. Users should be able to input a location (latitude & longitude) and a date, and the graph will adjust accordingly. I've incorpora ...

JavaScript code for displaying data sequentially one at a time

Hey there, I've developed a function that pulls data from a jsonp file. However, I'm looking to display this data one by one - starting with the vendor's name followed by their policyUrl. If you want to check out the source code, click on t ...

Fetching from the same origin results in a null comparison issue due to HTTP CORS restrictions

Encountering an issue where a simple same-origin fetch("fetch.xml") call fails, resulting in a console error message Access to fetch at 'http://127.0.0.1:8000/fetch.xml' from origin 'null' has been blocked by CORS policy: Th ...

Troubleshooting problem with Safari browser - AJAX Dropdown Menu issue

I have integrated a dynamic dropdown menu (implemented in a php website) that utilizes Ajax functionality to populate the dropdown options. This feature works flawlessly on Chrome and Firefox, but encounters issues on Safari. On Safari, the dropdown func ...

The responsive design of Bootstrap NavBar seems to be malfunctioning when viewed on an iPhone device

Having an issue in Bootstrap Studio that I can't seem to resolve. I've seen recommendations to add the following meta tag to the <head> section: meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0", bu ...

What is the best way to split a single column into two using blocks?

I am working with a container that currently has all its blocks lined up in a column. I need to divide them into two columns, with 5 blocks in each. Unfortunately, the plugin I am using generates the code for me and does not allow me to insert my own div e ...

Saving Multiple Rows from Datagridview into a Single Database using C#

I am currently working with 2 datagridviews and trying to figure out how to save them in a single database. To better illustrate my question, I have created a video demonstration directly from my desktop. You can watch it here: Youtube video link Additio ...