Skip to content

Instantly share code, notes, and snippets.

@dagezi
Created March 14, 2014 08:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dagezi/9544171 to your computer and use it in GitHub Desktop.
Save dagezi/9544171 to your computer and use it in GitHub Desktop.
sample code of MessageDigest
import java.security.MessageDigest;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Sha1 {
private static void sha1ByMap(String file) throws IOException, NoSuchAlgorithmException {
FileInputStream fis = new FileInputStream(file);
long size = fis.available();
FileChannel fileChan = fis.getChannel();
ByteBuffer bytes = fileChan.map(FileChannel.MapMode.READ_ONLY, 0L, size);
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(bytes);
byte[] digest = md.digest();
for (byte b : digest) {
System.out.print(String.format("%02x", b));
}
System.out.println("");
}
private static void sha1ByRead(String file) throws IOException, NoSuchAlgorithmException {
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[4096];
MessageDigest md = MessageDigest.getInstance("SHA-1");
int size = 0;
while ((size = fis.read(bytes)) > 0) {
md.update(bytes, 0, size);
}
byte[] digest = md.digest();
for (byte b : digest) {
System.out.print(String.format("%02x", b));
}
System.out.println("");
}
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
String file = args[0];
sha1ByMap(file);
sha1ByRead(file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment