乐趣区

关于amazon-web-services:Java实现AWS-S3-V4-Authorization自定义验证

前言

最近在开发文件存储服务,须要合乎 s3 的协定规范,能够间接接入 aws-sdk,本文针对 sdk 发出请求的鉴权信息进行重新组合再签名验证有效性,sdk 版本如下

        <dependency>
            <groupId>software.amazon.awssdk</groupId>
            <artifactId>s3</artifactId>
            <version>2.20.45</version>
        </dependency>

算法解析

首先对 V4 版本签名算法的数据结构及签名流程进行拆解剖析,以申请头签名为示例解说

signature = doSign(waitSignString)

签名示例

申请头签名

AWS4-HMAC-SHA256 Credential=admin/20230530/us-east-1/s3/aws4_request, SignedHeaders=amz-sdk-invocation-id;amz-sdk-request;host;x-amz-content-sha256;x-amz-date, Signature=6f50628a101b46264c7783937be0366762683e0d319830b1844643e40b3b0ed

Url 签名

http://localhost:8001/s3/kkk/test.docx?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230531T024715Z&X-Amz-SignedHeaders=host&X-Amz-Expires=300&X-Amz-Credential=admin%2F20230531%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=038e2ea71073761aa0370215621599649e9228177c332a0a79f784b1a6d9ee39

数据结构

waitSignString = doHex(【第一局部】+【第二局部】+【第三局部】+【第四局部】),每局部应用 \n 换行符连贯,第四局部不要加上换行符

第一局部

Algorithm – 用于创立标准申请的哈希的算法,对于 SHA-256,算法是 AWS4-HMAC-SHA256,则这部分的内容固定为

"AWS4-HMAC-SHA256" + "\n"

第二局部

RequestDateTime – 在凭证范畴内应用的日期和工夫,这个工夫为申请收回的工夫,间接从申请头获取 x -amz-date 即可,这部分内容为

request.getHeader("x-amz-date") + "\n"

第三局部

CredentialScope – 凭证范畴,这会将生成的签名限度在指定的区域和服务范畴内,该字符串采纳以下格局:YYYYMMDD/region/service/aws4_request

这部分由 4 个内容信息拼接组成

  • 申请工夫的 YYYYMMDD 格局
  • 存储区域
  • 存储服务
  • 申请头

这些信息咱们都能够从申请头的 Authorization 凭证提取出 Credential 局部进行拆分重新组合

        String[] parts = authorization.trim().split("\\,");
        String credential = parts[0].split("\\=")[1];
        String[] credentials = credential.split("\\/");
        String accessKey = credentials[0];
        if (!accessKeyId.equals(accessKey)) {return false;}
        String date = credentials[1];
        String region = credentials[2];
        String service = credentials[3];
        String aws4Request = credentials[4];

这部分内容为

date + "/" + region + "/" + service + "/" + aws4Request + "\n"

第四局部

HashedCanonicalRequest – 标准申请的哈希

这部分内容为

doHex(canonicalRequest)

canonicalRequest 具体拆解又能够 6 小局部组成,每局部应用 \n 换行符连贯,最初不要加上换行符

<HTTPMethod>\n
<CanonicalURI>\n
<CanonicalQueryString>\n
CanonicalHeaders>\n
<SignedHeaders>\n
<HashedPayload>
  • HTTPMethod

    代表申请的 HTTP 办法,例如 GET,POST,DELETE,PUT 等,间接从 request 获取即可

    这部分内容为

    String HTTPMethod = request.getMethod() + "\n"
  • CanonicalURI

    代表申请的路由局部,例如实现申请为 http://localhost:8001/s3/aaaa/ccc.txt,则该局部为 /s3/aaaa/ccc.txt

    须要进行 encode 操作,我这里间接获取则省略了这部分

    这部分内容为

    String CanonicalURI = request.getRequestURI().split("\\?")[0] + "\n";
  • CanonicalQueryString

    代表申请参数的拼接成字符串 key1=value1&key2=value2 这种模式,拼接的 key 须要依照字母排序

    value 须要进行 encode 操作,我这里间接获取则省略了这部分

            String queryString = ConvertOp.convert2String(request.getQueryString());
            if(!StringUtil.isEmpty(queryString)){Map<String, String> queryStringMap =  parseQueryParams(queryString);
                List<String> keyList = new ArrayList<>(queryStringMap.keySet());
                Collections.sort(keyList);
                StringBuilder queryStringBuilder = new StringBuilder("");
                for (String key:keyList) {queryStringBuilder.append(key).append("=").append(queryStringMap.get(key)).append("&");
                }
                queryStringBuilder.deleteCharAt(queryStringBuilder.lastIndexOf("&"));
            }
    
        public static Map<String, String> parseQueryParams(String queryString) {Map<String, String> queryParams = new HashMap<>();
            try {if (queryString != null && !queryString.isEmpty()) {String[] queryParamsArray = queryString.split("\\&");
    
                    for (String param : queryParamsArray) {String[] keyValue = param.split("\\=");
                        if (keyValue.length == 1) {String key = keyValue[0];
                            String value = "";
                            queryParams.put(key, value);
                        }
                        else if (keyValue.length == 2) {String key = keyValue[0];
                            String value = keyValue[1];
                            queryParams.put(key, value);
                        }
                    }
                }
            } catch (Exception e) {e.printStackTrace();
            }
            return queryParams;
        }

    这部分内容为

    String CanonicalQueryString = queryStringBuilder.toString() + "\n"
  • CanonicalHeaders

    代表申请头拼接成字符串 key:value 的模式,每个 head 局部应用 \n 换行符连贯,拼接的 key 须要依照字母排序

    签名的申请头从 Authorization 解析获取

            String signedHeader = parts[1].split("\\=")[1];
            String[] signedHeaders = signedHeader.split("\\;");
            String headString = "";
            for (String name : signedHeaders) {headString += name + ":" + request.getHeader(name) + "\n";
            }

    这部分内容为

    String CanonicalHeaders = headString + "\n"
  • SignedHeaders

    代表申请头的 key 局部,应用; 隔开

    这部分内容为从 Authorization 解析中获取

    这部分内容为

    String SignedHeaders = signedHeader + "\n"
  • HashedPayload

    代表申请 body 局部的签名,间接从 requet 的 head 提取 x -amz-content-sha256 内容

    这部分内容为

    String HashedPayload = Stringrequest.getHeader("x-amz-content-sha256")

doHex

本局部只是一个字符串转 16 进制的一个操作

    private String doHex(String data) {
        MessageDigest messageDigest;
        try {messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes("UTF-8"));
            byte[] digest = messageDigest.digest();
            return String.format("%064x", new java.math.BigInteger(1, digest));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {e.printStackTrace();
        }
        return null;
    }

签名流程

doSign 的流程为 doBytesToHex(doHmacSHA256(signatureKey,waitSignString))

doBytesToHex 为 byte 转 16 进制操作

    private String doBytesToHex(byte[] bytes) {char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars).toLowerCase();}

doHmacSHA256 为签名算法

    private byte[] doHmacSHA256(byte[] key, String data) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF8"));
    }

signatureKey 签名密钥由 secretAccessKey,申请工夫,存储区域,存储服务,申请头这 5 个因素进行叠加签名生成

        byte[] kSecret = ("AWS4" + secretAccessKey).getBytes("UTF8");
        byte[] kDate = doHmacSHA256(kSecret, date);
        byte[] kRegion = doHmacSHA256(kDate, region);
        byte[] kService = doHmacSHA256(kRegion, service);
        byte[] signatureKey = doHmacSHA256(kService, aws4Request);

将最终生成的再签名与 Authorization 中解析出的 Signature 进行比拟,统一则鉴权胜利

调试地位

调试过程中须要验证每局部的签名是否拼接编码正确,咱们须要和 sdk 生成的内容进行比对找出问题

调试 software.amazon.awssdk.auth.signer.internal 包下 AbstractAws4Signer 类的 doSign 类,获取 stringToSign 与你待签名字符串比对差别,源码如下

    protected Builder doSign(SdkHttpFullRequest request, Aws4SignerRequestParams requestParams, T signingParams, ContentChecksum contentChecksum) {Builder mutableRequest = request.toBuilder();
        AwsCredentials sanitizedCredentials = this.sanitizeCredentials(signingParams.awsCredentials());
        if (sanitizedCredentials instanceof AwsSessionCredentials) {this.addSessionCredentials(mutableRequest, (AwsSessionCredentials)sanitizedCredentials);
        }

        this.addHostHeader(mutableRequest);
        this.addDateHeader(mutableRequest, requestParams.getFormattedRequestSigningDateTime());
        mutableRequest.firstMatchingHeader("x-amz-content-sha256").filter((h) -> {return h.equals("required");
        }).ifPresent((h) -> {mutableRequest.putHeader("x-amz-content-sha256", contentChecksum.contentHash());
        });
        this.putChecksumHeader(signingParams.checksumParams(), contentChecksum.contentFlexibleChecksum(), mutableRequest, contentChecksum.contentHash());
        AbstractAws4Signer.CanonicalRequest canonicalRequest = this.createCanonicalRequest(request, mutableRequest, contentChecksum.contentHash(), signingParams.doubleUrlEncode(), signingParams.normalizePath());
        String canonicalRequestString = canonicalRequest.string();
        String stringToSign = this.createStringToSign(canonicalRequestString, requestParams);
        byte[] signingKey = this.deriveSigningKey(sanitizedCredentials, requestParams);
        byte[] signature = this.computeSignature(stringToSign, signingKey);
        mutableRequest.putHeader("Authorization", this.buildAuthorizationHeader(signature, sanitizedCredentials, requestParams, canonicalRequest));
        this.processRequestPayload(mutableRequest, signature, signingKey, requestParams, signingParams, contentChecksum.contentFlexibleChecksum());
        return mutableRequest;
    }

代码示例

通过拦截器进行验证的过程,残缺代码如下,兼容了一般申请的头部验证和文件下载 url 的签名验证

@Component
public class S3Intecept implements HandlerInterceptor {
    @Autowired
    private SystemConfig systemConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean flag = false;
        String authorization = request.getHeader("Authorization");
        if(!StringUtil.isEmpty(authorization)){flag = validAuthorizationHead(request, systemConfig.getUsername(), systemConfig.getPassword());
        }else{authorization = request.getParameter("X-Amz-Credential");
            if(!StringUtil.isEmpty(authorization)){flag = validAuthorizationUrl(request, systemConfig.getUsername(), systemConfig.getPassword());
            }
        }
        if(!flag){response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }
        return flag;
    }

    public boolean validAuthorizationHead(HttpServletRequest request, String accessKeyId, String secretAccessKey) throws Exception {String authorization = request.getHeader("Authorization");
        String requestDate = request.getHeader("x-amz-date");
        String contentHash = request.getHeader("x-amz-content-sha256");
        String httpMethod = request.getMethod();
        String uri = request.getRequestURI().split("\\?")[0];
        String queryString = ConvertOp.convert2String(request.getQueryString());
        // 示例
        //AWS4-HMAC-SHA256 Credential=admin/20230530/us-east-1/s3/aws4_request, SignedHeaders=amz-sdk-invocation-id;amz-sdk-request;host;x-amz-content-sha256;x-amz-date, Signature=6f50628a101b46264c7783937be0366762683e0d319830b1844643e40b3b0ed

        ///region authorization 拆分
        String[] parts = authorization.trim().split("\\,");
        // 第一局部 - 凭证范畴
        String credential = parts[0].split("\\=")[1];
        String[] credentials = credential.split("\\/");
        String accessKey = credentials[0];
        if (!accessKeyId.equals(accessKey)) {return false;}
        String date = credentials[1];
        String region = credentials[2];
        String service = credentials[3];
        String aws4Request = credentials[4];
        // 第二局部 - 签名头中蕴含哪些字段
        String signedHeader = parts[1].split("\\=")[1];
        String[] signedHeaders = signedHeader.split("\\;");
        // 第三局部 - 生成的签名
        String signature = parts[2].split("\\=")[1];
        ///endregion

        ///region 待签名字符串
        String stringToSign = "";
        // 签名由 4 局部组成
        //1-Algorithm – 用于创立标准申请的哈希的算法。对于 SHA-256,算法是 AWS4-HMAC-SHA256。stringToSign += "AWS4-HMAC-SHA256" + "\n";
        //2-RequestDateTime – 在凭证范畴内应用的日期和工夫。stringToSign += requestDate + "\n";
        //3-CredentialScope – 凭证范畴。这会将生成的签名限度在指定的区域和服务范畴内。该字符串采纳以下格局:YYYYMMDD/region/service/aws4_request
        stringToSign += date + "/" + region + "/" + service + "/" + aws4Request + "\n";
        //4-HashedCanonicalRequest – 标准申请的哈希。//<HTTPMethod>\n
        //<CanonicalURI>\n
        //<CanonicalQueryString>\n
        //<CanonicalHeaders>\n
        //<SignedHeaders>\n
        //<HashedPayload>
        String hashedCanonicalRequest = "";
        //4.1-HTTP Method
        hashedCanonicalRequest += httpMethod + "\n";
        //4.2-Canonical URI
        hashedCanonicalRequest += uri + "\n";
        //4.3-Canonical Query String
        if(!StringUtil.isEmpty(queryString)){Map<String, String> queryStringMap =  parseQueryParams(queryString);
            List<String> keyList = new ArrayList<>(queryStringMap.keySet());
            Collections.sort(keyList);
            StringBuilder queryStringBuilder = new StringBuilder("");
            for (String key:keyList) {queryStringBuilder.append(key).append("=").append(queryStringMap.get(key)).append("&");
            }
            queryStringBuilder.deleteCharAt(queryStringBuilder.lastIndexOf("&"));

            hashedCanonicalRequest += queryStringBuilder.toString() + "\n";}else{hashedCanonicalRequest += queryString + "\n";}
        //4.4-Canonical Headers
        for (String name : signedHeaders) {hashedCanonicalRequest += name + ":" + request.getHeader(name) + "\n";
        }
        hashedCanonicalRequest += "\n";
        //4.5-Signed Headers
        hashedCanonicalRequest += signedHeader + "\n";
        //4.6-Hashed Payload
        hashedCanonicalRequest += contentHash;
        stringToSign += doHex(hashedCanonicalRequest);
        ///endregion

        ///region 从新生成签名
        // 计算签名的 key
        byte[] kSecret = ("AWS4" + secretAccessKey).getBytes("UTF8");
        byte[] kDate = doHmacSHA256(kSecret, date);
        byte[] kRegion = doHmacSHA256(kDate, region);
        byte[] kService = doHmacSHA256(kRegion, service);
        byte[] signatureKey = doHmacSHA256(kService, aws4Request);
        // 计算签名
        byte[] authSignature = doHmacSHA256(signatureKey, stringToSign);
        // 对签名编码解决
        String strHexSignature = doBytesToHex(authSignature);
        ///endregion

        if (signature.equals(strHexSignature)) {return true;}
        return false;
    }

    public boolean validAuthorizationUrl(HttpServletRequest request, String accessKeyId, String secretAccessKey) throws Exception {String requestDate = request.getParameter("X-Amz-Date");
        String contentHash = "UNSIGNED-PAYLOAD";
        String httpMethod = request.getMethod();
        String uri = request.getRequestURI().split("\\?")[0];
        String queryString = ConvertOp.convert2String(request.getQueryString());
        // 示例
        //"http://localhost:8001/s3/kkk/%E6%B1%9F%E5%AE%81%E8%B4%A2%E6%94%BF%E5%B1%80%E9%A1%B9%E7%9B%AE%E5%AF%B9%E6%8E%A5%E6%96%87%E6%A1%A3.docx?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20230531T024715Z&X-Amz-SignedHeaders=host&X-Amz-Expires=300&X-Amz-Credential=admin%2F20230531%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=038e2ea71073761aa0370215621599649e9228177c332a0a79f784b1a6d9ee39

        ///region 参数筹备
        // 第一局部 - 凭证范畴
        String credential =request.getParameter("X-Amz-Credential");
        String[] credentials = credential.split("\\/");
        String accessKey = credentials[0];
        if (!accessKeyId.equals(accessKey)) {return false;}
        String date = credentials[1];
        String region = credentials[2];
        String service = credentials[3];
        String aws4Request = credentials[4];
        // 第二局部 - 签名头中蕴含哪些字段
        String signedHeader = request.getParameter("X-Amz-SignedHeaders");
        String[] signedHeaders = signedHeader.split("\\;");
        // 第三局部 - 生成的签名
        String signature = request.getParameter("X-Amz-Signature");
        ///endregion

        ///region 验证 expire
        String expires = request.getParameter("X-Amz-Expires");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime startDate = LocalDateTime.parse(requestDate,formatter);
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime localDateTime = startDate.atZone(ZoneId.of("UTC")).withZoneSameInstant(zoneId);
        startDate = localDateTime.toLocalDateTime();
        LocalDateTime endDate = startDate.plusSeconds(ConvertOp.convert2Int(expires));
        if(endDate.isBefore(LocalDateTime.now())){return false;}
        ///endregion

        ///region 待签名字符串
        String stringToSign = "";
        // 签名由 4 局部组成
        //1-Algorithm – 用于创立标准申请的哈希的算法。对于 SHA-256,算法是 AWS4-HMAC-SHA256。stringToSign += "AWS4-HMAC-SHA256" + "\n";
        //2-RequestDateTime – 在凭证范畴内应用的日期和工夫。stringToSign += requestDate + "\n";
        //3-CredentialScope – 凭证范畴。这会将生成的签名限度在指定的区域和服务范畴内。该字符串采纳以下格局:YYYYMMDD/region/service/aws4_request
        stringToSign += date + "/" + region + "/" + service + "/" + aws4Request + "\n";
        //4-HashedCanonicalRequest – 标准申请的哈希。//<HTTPMethod>\n
        //<CanonicalURI>\n
        //<CanonicalQueryString>\n
        //<CanonicalHeaders>\n
        //<SignedHeaders>\n
        //<HashedPayload>
        String hashedCanonicalRequest = "";
        //4.1-HTTP Method
        hashedCanonicalRequest += httpMethod + "\n";
        //4.2-Canonical URI
        hashedCanonicalRequest += uri + "\n";
        //4.3-Canonical Query String
        if(!StringUtil.isEmpty(queryString)){Map<String, String> queryStringMap =  parseQueryParams(queryString);
            List<String> keyList = new ArrayList<>(queryStringMap.keySet());
            Collections.sort(keyList);
            StringBuilder queryStringBuilder = new StringBuilder("");
            for (String key:keyList) {if(!key.equals("X-Amz-Signature")){queryStringBuilder.append(key).append("=").append(queryStringMap.get(key)).append("&");
                }
            }
            queryStringBuilder.deleteCharAt(queryStringBuilder.lastIndexOf("&"));

            hashedCanonicalRequest += queryStringBuilder.toString() + "\n";}else{hashedCanonicalRequest += queryString + "\n";}
        //4.4-Canonical Headers
        for (String name : signedHeaders) {hashedCanonicalRequest += name + ":" + request.getHeader(name) + "\n";
        }
        hashedCanonicalRequest += "\n";
        //4.5-Signed Headers
        hashedCanonicalRequest += signedHeader + "\n";
        //4.6-Hashed Payload
        hashedCanonicalRequest += contentHash;
        stringToSign += doHex(hashedCanonicalRequest);
        ///endregion

        ///region 从新生成签名
        // 计算签名的 key
        byte[] kSecret = ("AWS4" + secretAccessKey).getBytes("UTF8");
        byte[] kDate = doHmacSHA256(kSecret, date);
        byte[] kRegion = doHmacSHA256(kDate, region);
        byte[] kService = doHmacSHA256(kRegion, service);
        byte[] signatureKey = doHmacSHA256(kService, aws4Request);
        // 计算签名
        byte[] authSignature = doHmacSHA256(signatureKey, stringToSign);
        // 对签名编码解决
        String strHexSignature = doBytesToHex(authSignature);
        ///endregion

        if (signature.equals(strHexSignature)) {return true;}
        return false;
    }

    private String doHex(String data) {
        MessageDigest messageDigest;
        try {messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes("UTF-8"));
            byte[] digest = messageDigest.digest();
            return String.format("%064x", new java.math.BigInteger(1, digest));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {e.printStackTrace();
        }
        return null;
    }

    private byte[] doHmacSHA256(byte[] key, String data) throws Exception {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF8"));
    }

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    private String doBytesToHex(byte[] bytes) {char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars).toLowerCase();}

    public static Map<String, String> parseQueryParams(String queryString) {Map<String, String> queryParams = new HashMap<>();
        try {if (queryString != null && !queryString.isEmpty()) {String[] queryParamsArray = queryString.split("\\&");

                for (String param : queryParamsArray) {String[] keyValue = param.split("\\=");
                    if (keyValue.length == 1) {String key = keyValue[0];
                        String value = "";
                        queryParams.put(key, value);
                    }
                    else if (keyValue.length == 2) {String key = keyValue[0];
                        String value = keyValue[1];
                        queryParams.put(key, value);
                    }
                }
            }
        } catch (Exception e) {e.printStackTrace();
        }
        return queryParams;
    }

}
退出移动版