1、python3
#python 3.7
import time
import hmac
import hashlib
import base64
import urllib.request
timestamp = int(round(time.time() * 1000))
secret = 'this is secret'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.request.quote(base64.b64encode(hmac_code))
print(timestamp)
print(sign)
python2
import time
import hmac
import hashlib
import base64
import urllib
timestamp = long(round(time.time() * 1000))
secret = 'this is secret'
secret_enc = bytes(secret).encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = bytes(string_to_sign).encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)
php
<?php
$secret = 'this is secret';
$timestamp = (float)sprintf("%.0f", microtime(true) * 1000);
$data = sprintf("%s\n%s", $timestamp, $secret);
$sign = urlencode(base64_encode(hash_hmac('sha256', $data, $secret, true)));
var_dump($timestamp, $sign);
nodjs
mport crypto from 'crypto'
generateSign(timestamp: number) {
let str = `${timestamp}\n${secret}`
let hash = crypto
.createHmac('SHA256', secret)
.update(str, 'utf8')
.digest('base64')
hash = encodeURIComponent(hash)
return hash
}
调用方式:
async sendData(data: any) {
try {
let timestamp = +new Date()
let sign = this.generateSign(timestamp)
let url = `${this.baseUrl}?access_token=${token}×tamp=${timestamp}&sign=${sign}`
let result = await axois.post(url, data)
return result.data
} catch (error) {}
}
请求方式就会变成:https://www.baidu.com/access_token=XXXX×tamp=XXXX&sign=XXXX