fanchangjifen commented on issue #11929:
URL: https://github.com/apache/apisix/issues/11929#issuecomment-2606590936

   > Java示例(以Hmac-sha256算法实现为例)
   
   部分写法可能不是最优的方案,仅供参考.
   
   Date需要按照格林尼治时间进行格式化.
   
   Authorization部分需要注意空格和换行符.
   
   ```
   import com.alibaba.fastjson2.JSONObject;
   import org.apache.commons.codec.binary.Base64;
   import org.apache.commons.codec.digest.HmacAlgorithms;
   import org.apache.http.HttpResponse;
   import org.apache.http.client.methods.HttpGet;
   import org.apache.http.impl.client.CloseableHttpClient;
   import org.apache.http.impl.client.HttpClientBuilder;
   import org.apache.http.util.EntityUtils;
   import org.bouncycastle.util.encoders.Hex;
   
   import javax.crypto.Mac;
   import javax.crypto.SecretKey;
   import javax.crypto.spec.SecretKeySpec;
   import java.io.IOException;
   import java.nio.charset.StandardCharsets;
   import java.security.Security;
   import java.time.Instant;
   import java.time.LocalDateTime;
   import java.time.ZoneId;
   import java.time.format.DateTimeFormatter;
   import java.util.Date;
   import java.util.Locale;
   
   public class Test {
   
       private static final String keyId = "111111111111111";
   
       private static final String secretKey = "222222222222222";
   
       private static final String algorithm = "hmac-sha256";
   
       public static void main(String[] args) throws IOException {
           CloseableHttpClient httpClient = HttpClientBuilder.create().build();
           String uri = "/uri";
           HttpGet httpGet = new HttpGet("http://127.0.0.1:9080"; + uri);
   
           String requestDate = dateTimeMillis2GMTString(new 
Date().getTime(),"EEE, d MMM yyyy HH:mm:ss 'GMT'");
           StringBuilder signature = new StringBuilder()
                   .append(keyId).append("\n")
                   .append(HttpGet.METHOD_NAME).append(" 
").append(uri).append("\n")
                   //注意date后面空格
                   .append("date:").append(" 
").append(requestDate).append("\n");
           String xHmacSignature = hmacSha256Base64Str(secretKey, 
signature.toString());
           StringBuilder authorization = new StringBuilder()
                   .append("Signature").append(" 
").append("keyId=").append('\"').append(keyId).append('\"').append(",algorithm=").append('\"').append(algorithm).append('\"').append(",")
                   .append("headers=").append('\"').append("@request-target 
date").append('\"').append(",")
                   
.append("signature=").append('\"').append(xHmacSignature).append('\"');
           httpGet.setHeader("Date", requestDate.toString());
           httpGet.setHeader("Authorization",authorization.toString());
           System.out.println(JSONObject.toJSONString(httpGet));
           HttpResponse response = httpClient.execute(httpGet);
           System.out.println("请求响应状态" + 
response.getStatusLine().getStatusCode());
           String responseStr = EntityUtils.toString(response.getEntity(), 
StandardCharsets.UTF_8);
           System.out.println(responseStr);
       }
   
       public static String hmacSha256Base64Str(final String key, final String 
data) {
           try {
               final Mac mac = 
Mac.getInstance(HmacAlgorithms.HMAC_SHA_256.toString());
               final SecretKeySpec signingKey = new 
SecretKeySpec(key.getBytes(), mac.getAlgorithm());
               mac.init(signingKey);
               byte[] hmacShaBytes = 
mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
               return new String(Base64.encodeBase64(hmacShaBytes), 
StandardCharsets.UTF_8);
           } catch (Exception e) {
               e.printStackTrace();
           }
           return null;
       }
   
       public static String dateTimeMillis2GMTString(long time,String format){
           Instant instant = Instant.ofEpochMilli(time);
           ZoneId zone = ZoneId.of("GMT");
           return LocalDateTime.ofInstant(instant, 
zone).format(DateTimeFormatter.ofPattern(format, Locale.ENGLISH));
       }
   }
   ```


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to