具體過程參考官網開發者指南
轉載請註明出處
[我的博客]http://www.lostbug.cn
只記錄幾個要點
- 書寫上傳策略
public class ImagePutPolicy implements Serializable {
private String scope;
private long deadline;
private ReturnBody returnBody;
public ImagePutPolicy( String fileName) {
scope = QiNiuConstant.SAVESPACE+":"+fileName;
}
public long getDeadline() {
return deadline;
}
public void setDeadline(long deadline) {
this.deadline = System.currentTimeMillis()/1000+deadline;
}
public ReturnBody getReturnBody() {
return returnBody;
}
public void setReturnBody(ReturnBody returnBody) {
this.returnBody = returnBody;
}
- 將上傳策略Object 轉Json樣式字符串:
引用Google官方[Gson包]https://github.com/google/gson
Gson gson=new Gson();
String jsonObject= gson.toJson(mImagePutPolicy);
- 對JSON編碼的上傳策略進行URL安全的Base64編碼,得到待簽名字符數組
String encodedPutPolicy=Base64.encodeToString(jsonObject.getBytes(),Base64.URL_SAFE);
- 使用SecretKey對上一步生成的待簽名字符數組計算HMAC-SHA1簽名並進行URL安全的Base64編碼:
這是Android方法,然而用後是 bad token,原來android太智能,自動在後面加了”\n”,
encodedSign=hmacSha1(encodedPutPolicy,secretKey)
public static String hmacSha1(String base, String key)
throws NoSuchAlgorithmException, InvalidKeyException {
String type = "HmacSHA1";
SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
Mac mac = Mac.getInstance(type);
mac.init(secret);
byte[] digest = mac.doFinal(base.getBytes());
return Base64.encodeToString(digest, Base64.URL_SAFE).replaceAll("\n","");
}
好像android方法與Java方法產生不同結果,用JAVA方法,一切OK:
Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(StringUtils.utf8Bytes(QiNiuConstant.SECRETKEY), "HmacSHA1"));
String encodedSign = UrlSafeBase64.encodeToString(mac.doFinal(StringUtils.utf8Bytes(encodedPutPolicy)));
- 將AccessKey、encodedSign和encodedPutPolicy用:連接起來
String uploadToken = QiNiuConstant.ACCESSKEY + ":" + encodedSign + ":" + encodedPutPolicy;