How to use the HmacSHA256 function from crypto-js

Find comprehensive JavaScript crypto-js.HmacSHA256 code examples handpicked from public code repositorys.

crypto-js.HmacSHA256 is a method used for creating a hash-based message authentication code using the SHA256 algorithm.

330
331
332
333
334
335
336
337
338
339
function HMACEncrypt() {
    var text = "I love python!"
    var key = "secret"
    return CryptoJS.HmacMD5(text, key).toString();
    // return CryptoJS.HmacSHA1(text, key).toString();
    // return CryptoJS.HmacSHA256(text, key).toString();
}

console.log(HMACEncrypt())
```
fork icon34
star icon57
watch icon0

+ 7 other calls in file

123
124
125
126
127
128
129
130
131
132
  }
  let st: string = ''
  stk.split(',').map((item, index) => {
    st += `${item}:${getQueryString(url, item)}${index === stk.split(',').length - 1 ? '' : '&'}`
  })
  const hash2 = CryptoJS.HmacSHA256(st, hash1.toString()).toString(CryptoJS.enc.Hex)
  return encodeURIComponent(["".concat(timestamp.toString()), "".concat(fingerprint.toString()), "".concat(appId.toString()), "".concat(token), "".concat(hash2)].join(";"))
}

function requireConfig() {
fork icon17
star icon57
watch icon4

How does crypto-js.HmacSHA256 work?

crypto-js.HmacSHA256 is a method in the crypto-js library that computes the HMAC-SHA256 message authentication code for the provided message and key, using the SHA256 hash function and the HMAC construction. The HMAC-SHA256 algorithm takes two inputs: a message and a secret key. It produces a fixed-size output called a message authentication code (MAC) that can be used to verify the integrity and authenticity of the message. The MAC is computed by applying a hash function (SHA256 in this case) to the concatenation of the key and the message, with some additional padding and processing steps to ensure security. The crypto-js.HmacSHA256 method returns the MAC as a WordArray object, which can be converted to a string or a byte array as needed.

713
714
715
716
717
718
719
720
721
722
723


function taskUrl(functionId, body = {}) {
	let t = +new Date();
	let key = `lite-android&${JSON.stringify(body)}&android&3.1.0&${functionId}&${t}&846c4c32dae910ef`;
	const C = $.isNode() ? require("crypto-js") : CryptoJS;
	let sign = C.HmacSHA256(key, '12aea658f76e453faf803d15c40a72e0')
		.toString();
	return {
		url: `${JD_API_HOST}?functionId=${functionId}&body=${escape(JSON.stringify(body))}&appid=lite-android&client=android&uuid=846c4c32dae910ef&clientVersion=3.1.0&t=${t}&sign=${sign}`,
		headers: {
fork icon31
star icon49
watch icon3

+ 3 other calls in file

214
215
216
217
218
219
220
221
222
223
  // eslint-disable-next-line no-param-reassign
  config.data = undefined;
}
const message = baseMessage;
const hmacKey = CryptoJS.enc.Base64.parse(this.secretKey);
const signature = CryptoJS.HmacSHA256(message, hmacKey);
const signatureB64 = signature.toString(CryptoJS.enc.Base64);

return {
  ...config,
fork icon3
star icon3
watch icon1

+ 4 other calls in file

Ai Example

1
2
3
4
5
6
7
const CryptoJS = require("crypto-js");

const message = "Hello, world!";
const secretKey = "secret123";
const hash = CryptoJS.HmacSHA256(message, secretKey).toString(CryptoJS.enc.Hex);

console.log(hash); // output: 9628e3e3c9faeebb2b0a8a301a2d69c0b7e1b365a1b8c0b372f9cf0c0445cf35

In this example, we first require the crypto-js library. We then create a message variable containing a string, and a secretKey variable containing another string. We then pass these two values as arguments to the CryptoJS.HmacSHA256() function, which calculates the HMAC-SHA256 hash of the message using the secretKey. Finally, we convert the resulting hash to a hexadecimal string using CryptoJS.enc.Hex, and log it to the console.

99
100
101
102
103
104
105
106
107
108
}

__genSign(t, e) {
  const n = e.map(o => `${o.key}:${o.value}`).join('&');
  // var n = (0, u.default)(e).call(e, function (t) {return t.key + ':' + t.value;}).join('&');
  t = CryptoJS.HmacSHA256(n, t).toString(CryptoJS.enc.Hex);
  return {
    _stk: e.map(o => o.key).join(','),
    // _stk: (0, u.default)(e).call(e, function (t) {return t.key;}).join(','),
    _ste: 1,
fork icon3
star icon1
watch icon1

22
23
24
25
26
27
28
29
30
31
//   }).toString();
// };

const hmacSHA256 = (data, key) =>
  CryptoJS.enc.Base64.stringify(
    CryptoJS.HmacSHA256(data, CryptoJS.enc.Base64.parse(key))
  );

module.exports = {
  signingData,
fork icon2
star icon2
watch icon1

41
42
43
44
45
46
47
48
49
50
51
52
  return key;
}


// https://medium.com/@dimple.shanbhag/password-authentication-using-crypto-js-c278a4a1f4a9 (strategy 2)
function hashPassword(password) {
  const hash = CryptoJS.HmacSHA256(password, process.env.CRYPTO_KEY);
  return CryptoJS.enc.Base64.stringify(hash);
}


// Returns the user associated with an authentication key
fork icon0
star icon2
watch icon1

+ 6 other calls in file

86
87
88
89
90
91
92
93
94
95
},
hmacsha224() {
  return CryptoJS.HmacSHA224(this.text, this.serect).toString();
},
hmacsha256() {
  return CryptoJS.HmacSHA256(this.text, this.serect).toString();
},
hmacsha384() {
  return CryptoJS.HmacSHA384(this.text, this.serect).toString();
},
fork icon0
star icon1
watch icon1

+ 17 other calls in file

83
84
85
86
87
88
89
90
91
92
let hash1 = this.enCryptMethodJD(this.tk, this.fingerprint.toString(), timestamp.toString(), this.appId.toString(), CryptoJS).toString(CryptoJS.enc.Hex);
let st = '';
stk.split(',').map((item, index) => {
    st += `${item}:${getUrlData(url, item)}${index === stk.split(',').length - 1 ? '' : '&'}`;
})
const hash2 = CryptoJS.HmacSHA256(st, hash1.toString()).toString(CryptoJS.enc.Hex);
const enc = (["".concat(timestamp.toString()), "".concat(this.fingerprint.toString()), "".concat(this.appId.toString()), "".concat(this.tk), "".concat(hash2)].join(";"))
this.result['fingerprint'] = this.fingerprint;
this.result['timestamp'] = this.timestamp
this.result['stk'] = stk;
fork icon1
star icon0
watch icon1

+ 4 other calls in file

107
108
109
110
111
112
113
114
115
116
};

/* SHA256 hashing */
exports.SHA256 = function(text, key) {
    try {
        return typeof key !== undefined ? CryptoJS.HmacSHA256(text, key) : CryptoJS.SHA256(text);
    }
    catch (err) {
        throw "ERROR - utils/utilidades.js _ SHA256 methood";
    }
fork icon1
star icon0
watch icon2

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
function HMACEncrypt() {
    var text = "I love python!"
    var key = "secret111"   // 密钥文件
    // return CryptoJS.HmacMD5(text, key).toString();
    // return CryptoJS.HmacSHA1(text, key).toString();
    return CryptoJS.HmacSHA256(text, key).toString();
}
console.log(HMACEncrypt())

fork icon0
star icon0
watch icon2