Created
March 14, 2014 08:41
-
-
Save dagezi/9544171 to your computer and use it in GitHub Desktop.
sample code of MessageDigest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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