How to calculate SHA-256 checksum of S3 file content

萝らか妹 提交于 2019-12-08 06:02:24

问题


S3 out of the box provides the MD5 checksum of the S3 object content. But I need to calculate the SHA-256 checksum of the file content. The file could be large enough so I do not want to load the file in memory and calculate the checksum, instead I need a solution to calculate the checksum without loading the whole file in memory.


回答1:


It can be achieved by following steps in Java:

  1. Get InputStream of the S3 Object
  2. Use MessageDigest and DigestInputStream classes for the SHA-256 hash(or SHA-1 or MD5)

Following is the snippet on how to do it:

String getS3FileHash(AmazonS3 amazonS3, String s3bucket, String filePath) {
    try {
        InputStream inputStream = amazonS3.getObject(s3bucket, filePath).getObjectContent();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        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; 
}


来源:https://stackoverflow.com/questions/50226112/how-to-calculate-sha-256-checksum-of-s3-file-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!