[英]How to calculate SHA-256 checksum of S3 file content
S3 out of the box provides the MD5 checksum of the S3 object content. 开箱即用的S3提供S3对象内容的MD5校验和。 But I need to calculate the SHA-256 checksum of the file content.
但是我需要计算文件内容的SHA-256校验和。 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.
该文件可能足够大,所以我不想将文件加载到内存中并计算校验和,相反,我需要一种解决方案来计算校验和而不将整个文件加载到内存中。
It can be achieved by following steps in Java: 可以通过以下Java步骤来实现:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.