简体   繁体   中英

SHA256 HMAC does not give the expected answer

String stringToSign = "GET" + "\n" +
                    "webservices.amazon.com" + "\n" +
                    "/onca/xml" + "\n" +
                    "AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&ItemId=0679722769&Operation=ItemLookup&ResponeGroup=ItemAttributes%2COffers%2CImages%2CReviews&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&Version=2009-01-06";


    SecretKeySpec keySpec = new SecretKeySpec(
            "1234567890".getBytes(),
            "HmacSHA256");

    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(keySpec);


    byte[] result = mac.doFinal(stringToSign.getBytes());
    String encodedResult = Base64.encodeBase64String(result);
    System.out.println("encodedResult: "+encodedResult);

    String urlEncodedResult = URLEncoder.encode(encodedResult, "UTF-8").replace("+", "%2B").replace("*", "%2A").replace("%7E", "~");
    System.out.println("ulrEncodedResult: "+urlEncodedResult);

This is for the REST authentication for AWS. The result I get is: ulrEncodedResult: k1T%2FqvVoXgEvmdFhTEh71vLDznqEVCyKcslA5RRSB6s%3D

The expected result is: ulrEncodedResult: M%2Fy0%2BEAFFGaUAp4bWv%2FWEuXYah99pVsxvqtAuC8YN7I%3D

All the exact steps for authentication are show here: http://docs.aws.amazon.com/AWSECommerceService/2011-08-01/DG/rest-signature.html

Can anyone spot the mistake that I am making?

One concern is that this:

"1234567890".getBytes()

and this

stringToSign.getBytes()

don't specify the character encoding used (eg UTF8). It'll be dependent on your platform or JVM settings, and that may be different from what you want (which is, I suspect, UTF8). I would prefer to use the getBytes(CharSet) variant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM