生成AWS Signature v4签名以上载到s3(从v2迁移)

时间:2018-03-03 07:56:59

标签: java amazon-web-services amazon-s3

我目前的工作实现如下:

UI选择文件=>点击上传=>调用我的后端API来请求签名,因为我不想公开我的访问权限+ secretkey =>返回签名+ policy =>上传到s3。

这对于v2来说很好用。

String base64Policy = (new BASE64Encoder()).encode(policy.toString().getBytes("UTF-8")).replaceAll("\n", "").replaceAll("\r", "");

        Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA1"));
        String signature = (new BASE64Encoder()).encode(hmac.doFinal(base64Policy.getBytes("UTF-8"))).replaceAll("\n", "");

现在我到了一个有趣的位置,我的新桶位于不支持v2的区域。

我正在关注AWS文档,但我认为我误解了有效负载位。我是否真的需要在我的整个文件的sha256哈希中传递我的UI?因为那似乎有点痛苦,特别是因为我的文件可以是> 1演出。

我试图使用的代码:

        byte[] signatureKey = getSignatureKey(secretKey, LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")),  bucketRegion, "s3");
        StringBuilder sb = new StringBuilder();
        for (byte b : signatureKey) {
            sb.append(String.format("%02X", b));
        }

private static byte[] getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
        byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
        byte[] kDate = HmacSHA256(dateStamp, kSecret);
        byte[] kRegion = HmacSHA256(regionName, kDate);
        byte[] kService = HmacSHA256(serviceName, kRegion);
        byte[] kSigning = HmacSHA256("aws4_request", kService);
        return kSigning;
    }



private static byte[] HmacSHA256(String data, byte[] key) throws Exception {
        String algorithm="HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF8"));
    }

但是当我尝试使用其余代码时,这会产生无效的签名响应。

我是不是很努力,只是误解:https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html

任何帮助都会受到高度赞赏,因为我一直对着这种方式不屑一顾,我宁愿不要过多检修。

1 个答案:

答案 0 :(得分:2)

您可以使用标准SDK方法将文件上传到S3而不生成签名,请参阅documentation。 但是,如果您出于某种原因需要签名,我认为,生成签名的最简单方法是使用AWS SDK中的方法,请参阅以下扩展AWS4Signer的类:

public class AwsAuthUtil extends AWS4Signer {
    private String serviceName;
    private AWSCredentials credentials;
    private String region;

    public AwsAuthUtil(AWSCredentials credentials, String region, String serviceName) {
        this.credentials = credentials;
        this.region = region;
        this.serviceName = serviceName;
    }

    public String getSignature(String policy, LocalDateTime dateTime) {
        try {
            String dateStamp = dateTime.format(ofPattern("yyyyMMdd"));
            return Hex.encodeHexString(hmacSha256(newSigningKey(credentials, dateStamp, region, serviceName), policy));
        } catch (Exception e) {
            throw new RuntimeException("Error", e);
        }
    }

    private byte[] hmacSha256(byte[] key, String data) throws Exception {
        Mac mac = Mac.getInstance(SigningAlgorithm.HmacSHA256.name());
        mac.init(new SecretKeySpec(key, SigningAlgorithm.HmacSHA256.name()));
        return mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
    }
}

AWS4Signer来自

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk-s3</artifactId>
    <version>1.11.213</version>
</dependency>

AWSCredentials可以构建为

AWSCredentials awsCredentials = new BasicAWSCredentials(s3AccessKey, s3SecretKey);

您还应该在使用多部分数据时考虑http标头,例如,请参阅以下构建HttpEntity的方法

public HttpEntity buildPostMultipartDataEntity(String objectKey, byte[] data, String signature, LocalDateTime dateTime) {

    String dateTimeStr = dateTime.format(ofPattern("yyyyMMdd'T'HHmmss'Z'"));
    String date = dateTime.format(ofPattern("yyyyMMdd"));

    return MultipartEntityBuilder
        .create()
        .addTextBody("key", objectKey)
        .addTextBody("Policy", policy)
        .addTextBody("X-Amz-Signature", signature)
        .addTextBody("X-Amz-Algorithm", algorithm)
        .addTextBody("X-Amz-Date", dateTimeStr)
        .addTextBody("X-Amz-Credential", String.format("%s/%s/%s/s3/aws4_request", accessKey, date, region))
        .addBinaryBody("file", data)
        .build();
}