问题
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