How to get File both MD5 and SHA1 checksum at the same time when upload a new file?

 ̄綄美尐妖づ 提交于 2019-12-11 00:57:24

问题


I am working on a storage system. Users upload files to the server.

On the server side, I want to implement a program to get the checksums of the file using both MD5 and SHA1.

I know how to calculate checksums using DigestInputStream functions, but it seems only supports one method (either MD5 or SHA1) a time. How can I calculate both MD5 and SHA1 a the same time when dealing with the upload stream in JAVA?

Thanks guys


回答1:


Use two MessageDigest instances (one for MD5 and one for SHA1) and feed the bytes you read into both.




回答2:


as java-ish pseudocode, since you can look up the API for OpenSSL or BSafe or the Java Crypto API on your own...

Buffered reader = ...;
char[MY_ARRAY_SIZE] buf = ...;

while( true ) {
  int count = reader.read(buf, 0, buf.length);
  if( count == -1 ) { break };

  /* You'll need to check for the right API and handle errors yourself */
  md5.add(buf, count);
  sha256.add(buf, count);
}

String md5sum = base64(md5.finalize()); // assumes an appropriate base64 method
String sha256sum = base64(sha256.finalize());



来源:https://stackoverflow.com/questions/14610850/how-to-get-file-both-md5-and-sha1-checksum-at-the-same-time-when-upload-a-new-fi

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