kev*_*son 15 android amazon-s3 amazon-web-services
我一直在努力使用亚马逊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()));
Run Code Online (Sandbox Code Playgroud)
然后是我用来生成签名值的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
我使用了Amazon S3 Signature测试仪,我的字符串是正确的,但我从来没有得到正确的编码值.感谢您提供任何帮助或推动正确的方向.
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
String policy = (new BASE64Encoder()).encode(
policy_document.getBytes("UTF-8")).replaceAll("\n","").replaceAll("\r","");
Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(new SecretKeySpec(
aws_secret_key.getBytes("UTF-8"), "HmacSHA1"));
String signature = (new BASE64Encoder()).encode(
hmac.doFinal(policy.getBytes("UTF-8")))
.replaceAll("\n", "");
Run Code Online (Sandbox Code Playgroud)
[参考: https: //aws.amazon.com/articles/1434]
上面的链接还描述了 HTTP 请求中的输入参数。
| 归档时间: |
|
| 查看次数: |
4259 次 |
| 最近记录: |