SoFunction
Updated on 2025-04-05

How to use HMAC-SHA256 signature algorithm for vue

Generating signature algorithms in applications usually involves the following steps:

  • Collect data: Get the data that needs to be signed.
  • Organize data: sort, splice, encode and other processing according to the protocol or requirements.
  • Calculate signature: Use keys and algorithms (such as HMAC-SHA256) to calculate signatures.
  • Attach signature: Attach the signature to the request (such as HTTP Header, URL parameters, Request Body).
  • Commonly used signature algorithms include HMAC, RSA, etc. The following mainly introduces how to use HMAC-SHA256 to generate signatures.

Generate HMAC-SHA256 signature in

Install

npm install crypto-js

How to use vue2

<template>
  <div>
    <h1>Signature example</h1>
    <button @click="generateSignature">Generate a signature</button>
    <p>sign:{{ signature }}</p>
  </div>
</template>
<script>
import CryptoJS from "crypto-js";
export default {
  data() {
    return {
      signature: "",
    };
  },
  methods: {
    generateSignature() {
      // Sample data      const data = {
        message: "Hello, World!",
        timestamp: 111,
      };
      // Key (in real scenarios, it should be kept confidential and can be written casually, usually the backend returns to the frontend)      const secretKey = "111";
      // Sort and splice the data into strings      const sortedData = (data)
        .sort()
        .map((key) => `${key}=${data[key]}`)
        .join("&");
      // Calculate HMAC-SHA256 signature      const hash = CryptoJS.HmacSHA256(sortedData, secretKey);
      // Convert to string format       = (hash);
    },
  },
};
</script>
<style scoped>
h1 {
  font-size: 1.5em;
}
</style>

explain

  • Data sorting and splicing: (data).sort().map(…).join(‘&’); Sort the keys of the data and splice them into the format of key=value&key=value.
  • Calculate HMAC-SHA256: CryptoJS.HmacSHA256(sortedData, secretKey) Generates the HMAC-SHA256 signature.
  • Convert to string: (hash); Convert the signature to a hexadecimal string.

Practical application

In practical applications, signature generation often requires the following considerations:

  • Security: The key should be kept confidential and should not be exposed to the front-end code. Usually, signatures are generated on the backend, and the frontend is only responsible for sending data.
  • Coding processing: Some APIs require URL encoding or other specific format processing of data.
  • Timestamp or random number: To prevent replay attacks, it is usually necessary to include a timestamp or random number in the data.

Example of a complete HTTP request

<template>
  <div>
    <h1>Signature request example</h1>
    <button @click="sendSignedRequest">Send a signature request</button>
    <p>response:{{ response }}</p>
  </div>
</template>
<script>
import axios from 'axios';
import CryptoJS from 'crypto-js';
export default {
  data() {
    return {
      response: ''
    };
  },
  methods: {
    generateSignature(data, secretKey) {
      // Sort and splice the data into strings      const sortedData = (data)
        .sort()
        .map(key => `${key}=${data[key]}`)
        .join('&');
      // Calculate HMAC-SHA256 signature      const hash = CryptoJS.HmacSHA256(sortedData, secretKey);
      // Convert to string format      return (hash);
    },
    async sendSignedRequest() {
      const data = {
        message: 'Hello, API!',
        timestamp: (() / 1000)
      };
      const secretKey = 'your_secret_key';
      const signature = (data, secretKey);
      try {
        const response = await ('/data', data, {
          headers: {
            'X-Signature': signature
          }
        });
         = ;
      } catch (error) {
         = ;
      }
    }
  }
};
</script>
<style scoped>
h1 {
  font-size: 1.5em;
}
</style>

Sample code for HTML generation signature algorithm

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Signature example</title>
    <style>
      h1 {
        font-size: 1.5em;
      }
      .container {
        padding: 20px;
      }
      .button {
        display: inline-block;
        margin: 10px 0;
        padding: 10px 20px;
        background-color: #007bff;
        color: #fff;
        border: none;
        cursor: pointer;
        border-radius: 5px;
      }
      .button:hover {
        background-color: #0056b3;
      }
      .signature {
        font-family: monospace;
        margin-top: 10px;
      }
    </style>
    <!-- Introduced CryptoJS Library -->
    <script src="/ajax/libs/crypto-js/4.1.1/"></script>
  </head>
  <body>
    <div class="container">
      <h1>Signature example</h1>
      <button class="button" onclick="generateSignature()">Generate a signature</button>
      <p class="signature">sign:<span ></span></p>
    </div>
    <script>
      function generateSignature() {
        // Sample data        const data = {
          message: "Hello, World!",
          timestamp: (() / 1000),
        };
        // Key (in real scenarios, it should be kept confidential)        const secretKey = "your_secret_key";
        // Sort and splice the data into strings        const sortedData = (data)
          .sort()
          .map((key) => `${key}=${data[key]}`)
          .join("&");
        // Calculate HMAC-SHA256 signature        const hash = CryptoJS.HmacSHA256(sortedData, secretKey);
        // Convert to string format        const signature = (hash);
        // Show signature        ("signature").textContent = signature;
      }
    </script>
  </body>
</html>

This is the end of this article about vue using HMAC-SHA256 signature algorithm. For more related contents of vue HMAC-SHA256 signature algorithm, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!