Skip to content

Instantly share code, notes, and snippets.

@kennethliquidpubs
Created February 26, 2013 01:49
Show Gist options
  • Save kennethliquidpubs/5035111 to your computer and use it in GitHub Desktop.
Save kennethliquidpubs/5035111 to your computer and use it in GitHub Desktop.
Java AWS SDK S3 query string authentication
import java.util.Calendar;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.*;
import org.apache.commons.codec.binary.Hex;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.net.URLEncoder;
import org.apache.commons.codec.binary.Base64;
import java.io.UnsupportedEncodingException;
/* method */
public String getS3Url(String filename) {
// get your AWS credentials; remember to have AwsCredentials.properties at your resource load path
AWSCredentials credentials = new ClasspathPropertiesFileCredentialsProvider().getCredentials();
String accessKey = credentials.getAWSAccessKeyId();
String secretKey = credentials.getAWSSecretKey();
// set the expiration to one hour later
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.add(Calendar.HOUR, 1);
long secondsSinceEpoch = calendar.getTimeInMillis() / 1000L;
String canonicalizedResource = "/" + BUCKET_NAME + "/" + filename;
String stringToSign = "GET" + "\n\n\n" + secondsSinceEpoch + "\n" + canonicalizedResource;
String signature = null;
try {
byte[] keyBytes = secretKey.getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] digest = mac.doFinal(stringToSign.getBytes());
byte[] base64bytes = Base64.encodeBase64(digest);
String signedString = new String(base64bytes, "UTF-8");
signature = URLEncoder.encode(signedString, "UTF-8");
} catch (NoSuchAlgorithmException nsae) {
} catch (InvalidKeyException ike) {
} catch (UnsupportedEncodingException uee) {
}
return "https://s3.amazonaws.com" + canonicalizedResource + "?AWSAccessKeyId=" + accessKey + "&Expires=" + secondsSinceEpoch + "&Signature=" + signature;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment