我一直在使用亚马逊 S3 的 REST API 将文件从我的 Android 设备上传到我拥有的存储桶中。我有 KEY 和 SECRET_KEY,但不确定如何正确生成他们在请求中寻找的 signatureValue。我在他们的服务器上使用 HttpPut,但不确定如何正确生成 signatureValue。到目前为止,这就是我所拥有的:
HttpPut put = new HttpPut(URL);
String fmt = "EEE, dd MMM yyyy HH:mm:ss ";
SimpleDateFormat format = new SimpleDateFormat(fmt, Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String method = "PUT";
String contentType = "application/octet-stream";
String date = format.format(new Date()) + "GMT";
String bucket = "/test-bucket52809/";
StringBuffer buf = new StringBuffer();
buf.append(method).append("\n\n");
buf.append(contentType).append("\n");
buf.append(date).append("\n");
buf.append(bucket);
String signature = percentEncodeRfc3986(hmac(buf.toString()));
然后是我用来生成签名值的方法:
private void setupMac() throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException
{
byte[] secretyKeyBytes = KEY_SECRET.getBytes("UTF-8");
signingKey = new SecretKeySpec(secretyKeyBytes, "HmacSHA256");
mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
}
private String hmac(String stringToSign) {
String signature = null;
byte[] data;
byte[] rawHmac;
try {
data = stringToSign.getBytes("UTF-8");
rawHmac = mac.doFinal(data);
signature = new String(Base64.encode(rawHmac, Base64.DEFAULT));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("UTF-8" + " is unsupported!", e);
}
return signature;
}
private String percentEncodeRfc3986(String s) {
String out;
try {
out = URLEncoder.encode(s, "UTF-8").replace("+", "%20")
.replace("*", "%2A").replace("%7E", "~");
} catch (UnsupportedEncodingException e) {
out = s;
}
return out;
}
我使用了 Amazon S3 签名测试器,我的字符串是正确的,但我从来没有得到正确的编码值。感谢您提供任何帮助或推动正确的方向。