LoginSignup
1
2

More than 5 years have passed since last update.

【Java】s3の署名付きURLにアクセスする(署名バージョン2)

Posted at

awsの公式ページの通りにやっていきます。
https://docs.aws.amazon.com/ja_jp/AmazonS3/latest/dev/RESTAuthentication.html

認証ヘッダーに
Authorization: AWS AWSAccessKeyId:Signature
をつけるのですが、このSignatureを作るのがなかなか面倒です。

たまたま、Javaの案件で使うことがあったので、メモ代わりに投稿しておきます。

今回は、
https://[BUCKET].[ENDPOINT]/[FILE_NAME]
に証明書付きでアクセスしています。

  protected void getFile() throws NoSuchAlgorithmException, InvalidKeyException, ClientProtocolException, IOException {

    String resource= "/" + BUCKET + "/" +FILE_NAME;
    String contentType = "application/octet-stream";
    String md5 = "";
    String daHeader = "x-amz-meta-user:" + USER_ID;

  // 
    Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
    df.setTimeZone(c.getTimeZone());

    // StringToSignの作成
    String now = df.format(c.getTime());
    String stringToSign="GET" + "\n" + md5 + "\n" + contentType + "\n" + now + "\n" + daHeader + "\n" + resource;

    // signatureの作成
    SecretKeySpec sk = new SecretKeySpec(S3_SECRET.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(sk);
    byte[] dataBytes = stringToSign.getBytes("UTF-8");
    byte[] signatureBytes = mac.doFinal(dataBytes);
    String signature = new String(Base64.encodeBase64(signatureBytes), "UTF-8");


    // Getリクエスト
    HttpClient client = HttpClientBuilder.create().build(); 
    HttpGet request = new HttpGet("https://" + BUCKET + '.' + END_POINT + "/" + FILE_NAME);
    request.setHeader("Host", BUCKET + '.' + END_POINT);
    request.setHeader("Date", now.toString());
    request.setHeader("Content-Type", contentType);
    request.setHeader("Authorization", "AWS" + " " + S3_KEY + ':' + signature);
    request.setHeader("x-amz-meta-user", USER_ID);        

    HttpResponse response = client.execute(request);      
  }
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2