管理凭证示例代码

1.<path>或<path>?<query>部分,与<body>(即HTTP Body),用\n连接,得到signingStr
范例:

String signingStr = buildSigningStr("1", "1", "1");
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();
    }

2.使用secretKey对signingStr进行HMAC-SHA1签名,得到Sign
范例:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

String sign = getSignatureHmacSHA1(signingStr, secretKey);

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();
}

3.对签名数据Sign进行URL安全的Base64编码,得到encodeSign
范例:

String encodeSign = new String(urlSafeEncodeBytes(sign.getBytes("utf-8")), "utf-8"));

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;
}

private static byte[] encodeBase64Ex(byte[] src) {
// urlsafe version is not supported in version 1.4 or lower.
byte[] b64 = Base64.encodeBase64(src);

for (int i = 0; i < b64.length; i++) {
if (b64[i] == '/') {
b64[i] = '_';
} else if (b64[i] == '+') {
b64[i] = '-';
}
}
return b64;
}

4.将accessKey与encodeSign用:连接,得到管理凭证accessToken
范例:

String accessToken = String.format("%s:%s", accessKey, encodeSign);