1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package br.com.ingenieux.mojo.beanstalk.bundle;
18
19 import com.amazonaws.auth.AWSCredentials;
20
21 import org.apache.commons.codec.binary.Hex;
22
23 import java.text.SimpleDateFormat;
24 import java.util.Date;
25 import java.util.SimpleTimeZone;
26
27 import javax.crypto.Mac;
28 import javax.crypto.spec.SecretKeySpec;
29
30
31
32
33 public class RequestSignerBase {
34 public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
35
36 public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
37
38 protected static final String AWS_ALGORITHM = "HMAC-SHA256";
39
40 protected static final String TERMINATOR = "aws4_request";
41
42 protected static final String SCHEME = "AWS4";
43
44 static {
45 SimpleTimeZone timezone = new SimpleTimeZone(0, "UTC");
46
47 DATE_TIME_FORMAT.setTimeZone(timezone);
48 DATE_FORMAT.setTimeZone(timezone);
49 }
50
51 final AWSCredentials awsCredentials;
52
53 final String region;
54
55 final String service;
56
57 final Date date;
58
59 final String strDate;
60
61 final String strDateTime;
62
63 protected RequestSignerBase(AWSCredentials awsCredentials, String region, String service, Date date) {
64 this.awsCredentials = awsCredentials;
65 this.region = region;
66 this.service = service;
67 this.date = date;
68 this.strDate = DATE_FORMAT.format(date);
69 this.strDateTime = DATE_TIME_FORMAT.format(date);
70 }
71
72 protected byte[] deriveKey() {
73 String secret = RequestSigner.SCHEME.concat(awsCredentials.getAWSSecretKey());
74 byte[] kSecret = secret.getBytes();
75 byte[] kDate = hash(kSecret, strDate);
76 byte[] kRegion = hash(kDate, region);
77 byte[] kService = hash(kRegion, service);
78 byte[] key = hash(kService, RequestSigner.TERMINATOR);
79 return key;
80 }
81
82 protected byte[] hash(byte[] kSecret, String obj) {
83 try {
84 SecretKeySpec keySpec = new SecretKeySpec(kSecret, "HmacSHA256");
85
86 Mac mac = Mac.getInstance("HmacSHA256");
87
88 mac.init(keySpec);
89
90 return mac.doFinal(obj.getBytes("UTF-8"));
91 } catch (Exception exc) {
92 throw new RuntimeException(exc);
93 }
94 }
95
96 protected String hexEncode(String obj) {
97 return Hex.encodeHexString(obj.getBytes());
98 }
99 }