Last update:2023-12-27 17:29:31
Here are two straightforward examples demonstrating how to generate the authentication token:
Python Runnable Example
Substitute YOUR_ACCESS_KEY
, YOUR_ACCESS_KEY_SECRET
and YOUR_REQUEST_BODY
with your personal values in the sample code provided. Once you’ve updated the placeholders, run the code and the token value will be printed.
import hashlib
import hmac
import base64
import urllib
def build_signing_str(path, query, body):
connector = '\n'
signing_str = path
if query:
signing_str += '?' + query
signing_str += connector
if body:
signing_str += body
return signing_str
def get_signature_hmac_sha1(data, key):
hmac_sha1 = hmac.new(key.encode(), data.encode(), hashlib.sha1)
return hmac_sha1.hexdigest()
def url_safe_encode_bytes(src):
b64 = base64.urlsafe_b64encode(src.encode())
return b64.decode()
def generate_access_token(accessKey, encodeSign):
return "{}:{}".format(accessKey, encodeSign)
# Example Usage:
path = "/fops"
query = ""
body = "YOUR_REQUEST_BODY"
secretKey = "YOUR_ACCESS_KEY_SECRET"
accessKey = "YOUR_ACCESS_KEY"
signing_str = build_signing_str(path, query, body)
sign = get_signature_hmac_sha1(signing_str, secretKey)
encode_sign = url_safe_encode_bytes(sign)
access_token = generate_access_token(accessKey, encode_sign)
print(access_token)
Java Exmaple
// This function constructs the signing string by appending path, query and body with '\n' as a connector.
private String buildSigningStr(String path, String query, String body) {
char connector = '\n';
StringBuilder signingStrBuilder = new StringBuilder(path);
if (StringUtils.isNotEmpty(query)) signingStrBuilder.append('?').append(query);
signingStrBuilder.append(connector);
if (StringUtils.isNotEmpty(body)) signingStrBuilder.append(body);
return signingStrBuilder.toString();
}
// This function generates an HMAC-SHA1 signature from the given data and key.
public static String getSignatureHmacSHA1(byte[] data, String key) {
byte[] keyBytes = key.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac;
StringBuffer sb = new StringBuffer();
try {
mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data);
for (byte b : rawHmac) {
sb.append(byteToHexString(b));
}
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
// This function does url-safe base64 encoding. It pads the result with '=' until its length is a multiple of 4.
public static byte[] urlSafeEncodeBytes(byte[] src) {
if (src.length % 3 == 0) return encodeBase64Ex(src);
byte[] b = encodeBase64Ex(src);
if (b.length % 4 == 0) return b;
int pad = 4 - b.length % 4;
byte[] b2 = new byte[b.length + pad];
System.arraycopy(b, 0, b2, 0, b.length);
b2[b.length] = '=';
if (pad > 1) b2[b.length + 1] = '=';
return b2;
}
String accessToken = String.format("%s:%s", accessKey, encodeSign);