CryptoJS的hmac-sha1算法使用(转base64)——2022.11.18

CryptoJS下载地址

https://code.google.com/archive/p/crypto-js/

在线HMAC计算工具

在线HMAC计算工具

试用方法

1、引入js

import CryptoJS from "@/common/js/hmac-sha1/hmac-sha1.js";

2、此处是因为后端需求是返回base64字符串,所以把官方的转base64函数拿来用下

//转base64
function stringify(wordArray) {
	// Shortcuts
	var words = wordArray.words;
	var sigBytes = wordArray.sigBytes;
	var map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

	// Clamp excess bits
	wordArray.clamp();

	// Convert
	var base64Chars = [];
	for (var i = 0; i < sigBytes; i += 3) {
		var byte1 = (words[i >>> 2]       >>> (24 - (i % 4) * 8))       & 0xff;
		var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
		var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;

		var triplet = (byte1 << 16) | (byte2 << 8) | byte3;

		for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
			base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
		}
	}
	// Add padding
	var paddingChar = map.charAt(64);
	if (paddingChar) {
		while (base64Chars.length % 4) {
			base64Chars.push(paddingChar);
		}
	}
	return base64Chars.join('');
}

使用代码

let Timestamp = $myHelper.getNowFormatDate(); 
let key = type + '@'+ BleMAC + '@' + Timestamp; // {Type}@{BleMAC}@{Timestamp:yyyy-MM-ddTHH:mm:ss}
let txt = type + BleMAC + Timestamp; // {Type}{BleMAC}{Timestamp:yyyy-MM-ddTHH:mm:ss};
let Sign = stringify(CryptoJS.HmacSHA1(txt, key)); // 第一个参数为加密字符串,第二个参数为公共秘钥

你可能感兴趣的:(uni-app,javascript,前端,开发语言)