0

我正在使用 AWS 文档示例创建签名:

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"));
    }

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;
    }


String url = "https://iot.us-east-1.amazonaws.com/things?thingTypeName={thingTypeName}";

    @RequestMapping(value = "/things",produces=MediaType.APPLICATION_JSON_VALUE)
    public void getThingLists() throws Exception {
         SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
         String date=f.format(new Date());
            byte[] signature1 = getSignatureKey(secretKey, date, regionName, serviceName);
            String signature=Hex.encodeHexString(signature1);
            //String s = Base64.getEncoder().encodeToString(signature1);
            System.out.println("Signature : " + signature);
            String str="Signature="+signature ;
            str="AWS4-HMAC-SHA256 Credential=AKIA4XDJYZKLHCNVHNBA/20200724/us-east-1/execute-api/aws4_request, SignedHeaders=host;x-amz-date,"+str ;
            System.out.println(str);
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        headers.add("x-amz-date", date);
        headers.add("Authorization",str);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        // Send request with GET method, and Headers.
        ResponseEntity<String> response = restTemplate.exchange(url,
                HttpMethod.GET, entity, String.class,"SmartLed001");
        //return restTemplate.exchange(url, HttpMethod.GET, entity, String.class,"SmartLed001").getBody();
         String result = response.getBody();
            System.out.println(result);
    }

我得到的错误是:

org.springframework.web.client.HttpClientErrorException$Forbidden: 403 Forbidden
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:83)

我该如何解决这个问题?

4

0 回答 0