前端用crypto-js来进行加密,php使用hash_hmac()来进行加密,hash_equals()进行验证
crypto-js链接:
https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js
https://cdn.jsdelivr.net/npm/crypto-js@4.0.0/crypto-js.js
前端加密:前端对加密的密文转换了base64,后端拿到base64的直接进行比对,或者解除base64之后用密文比对是一样的
<script src="cdn.jsdelivr.net_npm_crypto-js@4.0.0_crypto-js.js"></script>
<script>
// HMAC-SHA256加密
// 定义要加密的消息和密钥
const message = "59172552507402230770";
const secretKey = "zQINfbbxbMGW";
// 执行 HMAC-SHA256 加密
const hash = CryptoJS.HmacSHA256(message, secretKey);
// 获取加密结果的十六进制表示
const encryptedMessage = hash.toString(CryptoJS.enc.Hex);
function baseToa(str) {
// 对字符串进行编码
var encode = encodeURI(str)
// 对编码的字符串转化base64
var base64 = btoa(encode)
return base64
}
console.log(baseToa(encryptedMessage));
</script>
php后端加密和验签:
$secret = 'mysecretkey';
$message = 'hello world';//接口参数如果是数组要转json
$hash = hash_hmac('sha256', $message, $secret);
//echo $hash;
//验证
$computedHash = hash_hmac('sha256', $message, $secret);
$expectedHash = 'MTBhNzRhZTQ0MTczYWVjNWZmNDgxNDY4MGI5NjBkMTAzMWVlZWNiNWEzNDczMjgzMTQzOTUzOWRlOTM1MmZmMg==';
$expectedHash = base64_decode($expectedHash);
if (hash_equals($expectedHash, $computedHash)) {
echo "加密结果验证通过";
} else {
echo "加密结果验证失败";
}
接口传输中每次密文都是变动的,参数中可以传入当前时间,判断当前时间与前端传递时间不能超过10分钟
// 获取当前时间的时间戳
$currentTimestamp = time();
// 假设传入的时间为 "2023-10-18 09:30:00"
$incomingTime = "2023-10-18 15:09:00";
$incomingTimestamp = strtotime($incomingTime);
// 计算当前时间和传入时间的差值(以秒为单位)
$timeDifference = ($currentTimestamp - $incomingTimestamp);
// 判断时间差是否超过10分钟(600秒)
if ($timeDifference > 600) {
echo "传入的时间超过了10分钟";
} else {
echo "传入的时间没有超过10分钟";
}