AWS S3 - Etag Sha256而不是Md5

时间:2017-05-22 07:53:19

标签: amazon-web-services amazon-s3

我想使用Sha256作为对象的校验和。 但看起来,亚马逊在ETag中使用了md5。

有解决方法吗?

2 个答案:

答案 0 :(得分:2)

不幸的是,没有直接的方法让S3使用SHA256进行ETag。您可以使用S3元数据作为解决方法。为此,您可以自己计算SHA256校验和,并使用用户定义的S3对象元数据为每次上载设置它。用户定义的元数据只是您可以分配给对象的一组键值对。您必须在GET对象时设置校验和,并在HEAD / public static func serializeResponseString( encoding: String.Encoding?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<String> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName)) ) } let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 if let string = String(data: validData, encoding: actualEncoding) { return .success(string) } else { return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) } } 对象上进行比较。

S3文档中提供了更多信息: http://docs.aws.amazon.com/AmazonS3/latest/dev/UsingMetadata.html

答案 1 :(得分:0)

请参阅:How to calculate SHA-256 checksum of S3 file content

可以通过以下Java步骤来实现:

  1. 获取S3对象的InputStream
  2.   

    InputStream inputStream = amazonS3.getObject(bucket,   文件).getObjectContent();

    1. 将MessageDigest和DigestInputStream类用于SHA-256哈希

      public static String getHash(InputStream inputStream, String algorithm) {
          try {
              MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
              DigestInputStream digestInputStream = new DigestInputStream(inputStream, messageDigest);
              byte[] buffer = new byte[4096];
              int count = 0;
              while (digestInputStream.read(buffer) > -1) {
                  count++;
              }
              log.info("total read: " + count);
              MessageDigest digest = digestInputStream.getMessageDigest();
              digestInputStream.close();
              byte[] md5 = digest.digest();
              StringBuilder sb = new StringBuilder();
              for (byte b: md5) {
                  sb.append(String.format("%02X", b));
              }
              return sb.toString().toLowerCase();
          } catch (Exception e) {
              log.error(e);
          }
          return null;
      }