CryptoJS和pbkdf2的加密使用
作者:互联网
一、CryptoJS加密,基本使用,最新支持的是256哈希码
if (signatureVersion === "1.0") {
words = CryptoJS.HmacSHA1(param, key);
} else {
words = CryptoJS.HmacSHA256(param, key);
}
var base64String = CryptoJS.enc.Base64.stringify(words);
新老算法支持:
/*
* @Author: caoyi
* @Date: 2021-11-17 15:58:07
* @LastEditTime: 2021-11-17 16:53:15
* @LastEditors: Please set LastEditors
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: \share_album\src\utils\js\assign.js
*/
const CryptoJS = require("crypto-js");
/**
* @param {*} key AppKey
* @param {*} method HttpVerb 比如:POST、GET
* @param {*} date 填空,当前不判断
* @param {*} contentType content-Type application/json;charset=UTF-8
* @param {*} md5 请求data的MD5值,不能为空
* @param {*} requestParam 请求地址和参数信息,不包括Http-Header
* @param {*} signatureVersion 加密版本号1.0/2.0
*/
function getSign(
key,
method,
date,
contentType,
md5,
requestParam,
signatureVersion
) {
var param = method;
param += "\n";
if (md5 == undefined) md5 = "";
param += md5;
param += "\n";
param += contentType;
param += "\n";
param += date;
param += "\n";
if (requestParam == undefined) requestParam = "";
if (requestParam != "") {
param += requestParam;
}
console.log("ssigData:\n" + param);
var words;
if (signatureVersion === "1.0") {
words = CryptoJS.HmacSHA1(param, key);
} else {
words = CryptoJS.HmacSHA256(param, key);
}
var base64String = CryptoJS.enc.Base64.stringify(words);
console.log(base64String);
var ssig = base64String.substr(5, 10);
var ssigEncode = encodeURIComponent(ssig);
return ssigEncode;
}
export function ssigValue(
key,
method,
date,
contentType,
md5,
requestParam,
signatureVersion
) {
return getSign(
key,
method,
date,
contentType,
md5,
requestParam,
signatureVersion
);
}
//生成从minNum到maxNum的随机数
export function randomNum(minNum, maxNum) {
switch (arguments.length) {
case 1:
return parseInt(Math.random() * minNum + 1, 10);
break;
case 2:
return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
break;
default:
return 0;
break;
}
}
注意:若使用CryptoJS加密,使用utf8转化生成array对象之后,千万不能取子字段值:words,会导致报错:
二、pbkdf2的使用
pbkdf2 - npm 此链接依赖于最新的sha256算法,所以安装下面的插件就可以
pbkdf2-sha256 - PBKDF2 using SHA256 HMAC - CryptoCoinJS
使用:
export function getPdkdSign(url, body) {
const appId = "d83kd93k2b9d916"
const appSecret = "a3jh2rj46hktg690bfdasjd0s0d87fc"
const timestamp = parseInt(Date.parse(new Date()) / 1000)
const nonce_divisor = 99
const src = "lexar"+JSON.stringify(body)+appSecret+timestamp
const iterations = (timestamp % nonce_divisor) + 1 // 取余 1-99次
const dk = pbkdf2(src, appSecret, iterations, 64)
const sign = dk.toString('base64').replace(/\+/g, '-').replace(/\//g, "_")
return {
options: {
'X-API-SIGN': sign
},
timestamp,
appId
// url: `${url}?appId=${appId}×tamp=${timestamp}`
}
}
标签:加密,key,requestParam,pbkdf2,param,words,const,CryptoJS 来源: https://blog.csdn.net/qq_32885597/article/details/121947063