如何在Java中生成AWS4签名

时间:2019-05-23 06:31:28

标签: java

//以下是用于生成aws版本4签名的工作代码

public static void main(String [] args){         尝试{             新的GenerateAWSS3Signature()。generateSignature(“ / path / to / s3storage / test1.csv”,generateDateTimeStamp(),                     “ text / plain”,“ awsAccessKeyId”,“ awsSecretKey”,“ filecontent”);         } catch(Exception e){             e.printStackTrace();         }     }

public String generateSignature(String lcl_filePath, String lcl_dateTimeStamp, String contentType,
        String awsAccessKeyId, String awsSecretKey, String payload) {
    String authorization = "";
    try {
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
        Date date1 = dt1.parse(lcl_dateTimeStamp);
        SimpleDateFormat dt2 = new SimpleDateFormat("yyyyMMdd");
        String lcl_dateStamp = dt2.format(date1);

        System.out.println("lcl_dateStamp: " + lcl_dateStamp);
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashPayloadInBytes = md.digest(payload.getBytes(StandardCharsets.UTF_8));
        StringBuilder payloadSb = new StringBuilder();
        for (byte b : hashPayloadInBytes) {
            payloadSb.append(String.format("%02x", b));
        }
        String hashPayload = payloadSb.toString();

        StringBuffer canonicalRequest = new StringBuffer();
        canonicalRequest.append("PUT").append("\n");
        canonicalRequest.append(lcl_filePath).append("\n\n");
        canonicalRequest.append("content-type:" + contentType).append("\n");
        canonicalRequest.append("host:s3-url-hostname").append("\n");
        canonicalRequest.append("x-amz-content-sha256:" + hashPayload).append("\n");
        canonicalRequest.append("x-amz-date:" + lcl_dateTimeStamp).append("\n\n");
        canonicalRequest.append("content-type;host;x-amz-content-sha256;x-amz-date").append("\n");
        canonicalRequest.append(hashPayload);

        System.out.println(lcl_dateTimeStamp);
        System.out.println(hashPayload);
        System.out.println(canonicalRequest.toString());

        byte[] hashCanonicalReqInBytes = md.digest(canonicalRequest.toString().getBytes(StandardCharsets.UTF_8));

        StringBuilder hashCanonicalSb = new StringBuilder();
        for (byte b : hashCanonicalReqInBytes) {
            hashCanonicalSb.append(String.format("%02x", b));
        }

        StringBuffer sringToSignSb = new StringBuffer();
        sringToSignSb.append("AWS4-HMAC-SHA256").append("\n");
        sringToSignSb.append(lcl_dateTimeStamp).append("\n");
        sringToSignSb.append(lcl_dateStamp + "/" + "ap-south-1/s3/aws4_request").append("\n");
        sringToSignSb.append(hashCanonicalSb.toString());
        String stringToSign = sringToSignSb.toString();
        System.out.println(stringToSign);
        byte[] kSigning = getSignatureKey(awsSecretKey, lcl_dateStamp, "ap-south-1", "s3");
        String signature = Hex.encodeHexString(kSigning);
        authorization = "AWS4-HMAC-SHA256 Credential=" + awsAccessKeyId + 
"/" + lcl_dateStamp
                + "/ap-south-1/s3/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature="
                + signature;
        System.out.println(authorization);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return authorization;
}

public static String generateDateTimeStamp() {
    SimpleDateFormat dt1 = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
    dt1.setTimeZone(TimeZone.getTimeZone("IST"));
    String dateStamp = dt1.format(new Date());
    return dateStamp;
}

public static String generateDate() {
    SimpleDateFormat dt1 = new SimpleDateFormat("yyyyMMdd");
    dt1.setTimeZone(TimeZone.getTimeZone("GMT"));
    String dateStamp = dt1.format(new Date());
    return dateStamp;
}

public 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("UTF-8"));
}

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

public String generateContentHashing(String payload) {
    StringBuilder payloadSb = new StringBuilder();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[] hashPayloadInBytes = md.digest(payload.getBytes(StandardCharsets.UTF_8));
        for (byte b : hashPayloadInBytes) {
            payloadSb.append(String.format("%02x", b));
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return payloadSb.toString();
}

0 个答案:

没有答案