上传凭证示例代码

1.生成putPolicy JSON串
范例:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

PutPolicy putPolicy = new PutPolicy();
putPolicy.setDeadline();
// .... setter

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.writeValueAsString(putPolicy);

2.对putPolicy进行URL安全的Base64编码,得到encodePutPolicy
范例:

import org.apache.commons.codec.binary.Base64;

String encodePutPolicy = new String(urlSafeEncodeBytes(putPolicy.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;
}

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

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

String sign = getSignatureHmacSHA1(encodePutPolicy.getBytes(CharEncoding.UTF_8), 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();
}

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

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

5.将accessKey、encodedSign和encodePutPolicy用:连接起来,得到上传凭证uploadToken
范例:

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