获取文件';Java中的MD5校验和
我希望使用Java来获取文件的MD5校验和。我真的很惊讶,但我还没有找到任何显示如何获取文件的MD5校验和的内容 它是如何完成的?有一个使用该类的示例 检查该页面,查看使用CRC32和SHA-1的示例获取文件';Java中的MD5校验和,java,md5,checksum,sha-1,crc32,bcrypt,scrypt,sha-256,Java,Md5,Checksum,Sha 1,Crc32,Bcrypt,Scrypt,Sha 256,我希望使用Java来获取文件的MD5校验和。我真的很惊讶,但我还没有找到任何显示如何获取文件的MD5校验和的内容 它是如何完成的?有一个使用该类的示例 检查该页面,查看使用CRC32和SHA-1的示例 import java.io.*; import java.security.MessageDigest; public class MD5Checksum { public static byte[] createChecksum(String filename) throws Exc
import java.io.*;
import java.security.MessageDigest;
public class MD5Checksum {
public static byte[] createChecksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
// see this How-to for a faster way to convert
// a byte array to a HEX string
public static String getMD5Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static void main(String args[]) {
try {
System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
// output :
// 0bb2827c5eacf570b6064e24e0e6653b
// ref :
// http://www.apache.org/dist/
// tomcat/tomcat-5/v5.5.17/bin
// /apache-tomcat-5.5.17.exe.MD5
// 0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
}
catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
导入java.security.MessageDigest;
公共类MD5Checksum{
公共静态字节[]createChecksum(字符串文件名)引发异常{
InputStream fis=新文件InputStream(文件名);
字节[]缓冲区=新字节[1024];
MessageDigest complete=MessageDigest.getInstance(“MD5”);
国际货币联盟;
做{
numRead=fis.read(缓冲区);
如果(numRead>0){
完成。更新(缓冲区,0,numRead);
}
}而(numRead!=-1);
fis.close();
返回complete.digest();
}
//请参见“如何转换”以了解更快的转换方法
//将字节数组转换为十六进制字符串
公共静态字符串getMD5Checksum(字符串文件名)引发异常{
字节[]b=创建校验和(文件名);
字符串结果=”;
for(int i=0;i
这里有一个使用该类的示例
检查该页面,查看使用CRC32和SHA-1的示例
import java.io.*;
import java.security.MessageDigest;
public class MD5Checksum {
public static byte[] createChecksum(String filename) throws Exception {
InputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
// see this How-to for a faster way to convert
// a byte array to a HEX string
public static String getMD5Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result += Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static void main(String args[]) {
try {
System.out.println(getMD5Checksum("apache-tomcat-5.5.17.exe"));
// output :
// 0bb2827c5eacf570b6064e24e0e6653b
// ref :
// http://www.apache.org/dist/
// tomcat/tomcat-5/v5.5.17/bin
// /apache-tomcat-5.5.17.exe.MD5
// 0bb2827c5eacf570b6064e24e0e6653b *apache-tomcat-5.5.17.exe
}
catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.*;
导入java.security.MessageDigest;
公共类MD5Checksum{
公共静态字节[]createChecksum(字符串文件名)引发异常{
InputStream fis=新文件InputStream(文件名);
字节[]缓冲区=新字节[1024];
MessageDigest complete=MessageDigest.getInstance(“MD5”);
国际货币联盟;
做{
numRead=fis.read(缓冲区);
如果(numRead>0){
完成。更新(缓冲区,0,numRead);
}
}而(numRead!=-1);
fis.close();
返回complete.digest();
}
//请参见“如何转换”以了解更快的转换方法
//将字节数组转换为十六进制字符串
公共静态字符串getMD5Checksum(字符串文件名)引发异常{
字节[]b=创建校验和(文件名);
字符串结果=”;
for(int i=0;i
有一个输入流修饰符,java.security.DigestInputStream
,这样您就可以像平常一样在使用输入流时计算摘要,而不必对数据进行额外的传递
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
DigestInputStream dis = new DigestInputStream(is, md))
{
/* Read decorated stream (dis) to EOF as normal... */
}
byte[] digest = md.digest();
有一个输入流修饰符,
java.security.DigestInputStream
,这样您就可以在使用输入流时像平常一样计算摘要,而不必额外传递数据
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = Files.newInputStream(Paths.get("file.txt"));
DigestInputStream dis = new DigestInputStream(is, md))
{
/* Read decorated stream (dis) to EOF as normal... */
}
byte[] digest = md.digest();
我最近不得不对一个动态字符串执行此操作,
MessageDigest
可以用多种方式表示哈希。要像使用命令一样获得文件的签名,我必须执行以下操作:
try {
String s = "TEST STRING";
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes(),0,s.length());
String signature = new BigInteger(1,md5.digest()).toString(16);
System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
这显然不能回答您关于如何专门为文件执行此操作的问题,上面的答案很好地解决了这个问题。我只是花了很多时间让总和看起来像大多数应用程序的显示,我想你可能会遇到同样的麻烦 我最近不得不对一个动态字符串执行此操作,
MessageDigest
可以用多种方式表示哈希。要像使用命令一样获得文件的签名,我必须执行以下操作:
try {
String s = "TEST STRING";
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes(),0,s.length());
String signature = new BigInteger(1,md5.digest()).toString(16);
System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}
这显然不能回答您关于如何专门为文件执行此操作的问题,上面的答案很好地解决了这个问题。我只是花了很多时间让总和看起来像大多数应用程序的显示,我想你可能会遇到同样的麻烦 从库中使用:
从图书馆使用:
如果您使用ANT进行构建,这非常简单。将以下内容添加到build.xml中:
<checksum file="${jarFile}" todir="${toDir}"/>
其中,jarFile是要生成MD5的JAR,toDir是要放置MD5文件的目录
如果您使用ANT进行构建,这非常简单。将以下内容添加到build.xml中:
<checksum file="${jarFile}" todir="${toDir}"/>
其中,jarFile是要生成MD5的JAR,toDir是要放置MD5文件的目录
我们使用的代码与上一篇文章中使用的代码类似
...
String signature = new BigInteger(1,md5.digest()).toString(16);
...
但是,请注意在此处使用biginger.toString()
,因为它将截断前导零。。。
(例如,尝试s=“27”
,校验和应为“02e74f10e0327ad868d138f2b4fdd6f0”
)
我支持使用ApacheCommons编解码器的建议,我用它替换了我们自己的代码。我们使用的是代码t
HashCode md5 = Files.hash(file, Hashing.md5());
byte[] md5Bytes = md5.asBytes();
String md5Hex = md5.toString();
HashCode crc32 = Files.hash(file, Hashing.crc32());
int crc32Int = crc32.asInt();
// the Checksum API returns a long, but it's padded with 0s for 32-bit CRC
// this is the value you would get if using that API directly
long checksumResult = crc32.padToLong();
public static void main(String[] args) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++) {
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
System.out.println("Digest(in hex format):: " + sb.toString());
}
DigestUtils.md5DigestAsHex(FileUtils.readFileToByteArray(file))
DigestUtils.md5Hex(FileUtils.readFileToByteArray(file))
public String checksum(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er =
MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0)
md5er.update(buffer, 0, read);
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null)
return null;
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
public static HashCode hash(File file,
HashFunction hashFunction)
throws IOException
Computes the hash code of the file using hashFunction.
Parameters:
file - the file to read
hashFunction - the hash function to use to hash the data
Returns:
the HashCode of all of the bytes in the file
Throws:
IOException - if an I/O error occurs
Since:
12.0
public static String getMd5OfFile(String filePath)
{
String returnVal = "";
try
{
InputStream input = new FileInputStream(filePath);
byte[] buffer = new byte[1024];
MessageDigest md5Hash = MessageDigest.getInstance("MD5");
int numRead = 0;
while (numRead != -1)
{
numRead = input.read(buffer);
if (numRead > 0)
{
md5Hash.update(buffer, 0, numRead);
}
}
input.close();
byte [] md5Bytes = md5Hash.digest();
for (int i=0; i < md5Bytes.length; i++)
{
returnVal += Integer.toString( ( md5Bytes[i] & 0xff ) + 0x100, 16).substring( 1 );
}
}
catch(Throwable t) {t.printStackTrace();}
return returnVal.toUpperCase();
}
byte[] b = Files.readAllBytes(Paths.get("/path/to/file"));
byte[] hash = MessageDigest.getInstance("MD5").digest(b);
String expected = "2252290BC44BEAD16AA1BF89948472E8";
String actual = DatatypeConverter.printHexBinary(hash);
System.out.println(expected.equalsIgnoreCase(actual) ? "MATCH" : "NO MATCH");
String path = "your complete file path";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(Files.readAllBytes(Paths.get(path)));
byte[] digest = md.digest();
System.out.println(Arrays.toString(digest));
String digestInHex = DatatypeConverter.printHexBinary(digest).toUpperCase();
System.out.println(digestInHex);
public String calcMD5() throws Exception{
byte[] buffer = new byte[8192];
MessageDigest md = MessageDigest.getInstance("MD5");
DigestInputStream dis = new DigestInputStream(new FileInputStream(new File("Path to file")), md);
try {
while (dis.read(buffer) != -1);
}finally{
dis.close();
}
byte[] bytes = md.digest();
// bytesToHex-method
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
String checksum = DigestUtils.md5Hex(new FileInputStream(filePath));
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class Checksum {
/**
* Generates an MD5 checksum as a String.
* @param file The file that is being checksummed.
* @return Hex string of the checksum value.
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static String generate(File file) throws NoSuchAlgorithmException,IOException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(Files.readAllBytes(file.toPath()));
byte[] hash = messageDigest.digest();
return DatatypeConverter.printHexBinary(hash).toUpperCase();
}
public static void main(String argv[]) throws NoSuchAlgorithmException, IOException {
File file = new File("/Users/foo.bar/Documents/file.jar");
String hex = Checksum.generate(file);
System.out.printf("hex=%s\n", hex);
}
}
hex=B117DD0C3CBBD009AC4EF65B6D75C97B
public static String hashFile(String algorithm, File f) throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
try(BufferedInputStream in = new BufferedInputStream((new FileInputStream(f)));
DigestOutputStream out = new DigestOutputStream(OutputStream.nullOutputStream(), md)) {
in.transferTo(out);
}
String fx = "%0" + (md.getDigestLength()*2) + "x";
return String.format(fx, new BigInteger(1, md.digest()));
}
hashFile("SHA-512", Path.of("src", "test", "resources", "some.txt").toFile());
"e30fa2784ba15be37833d569280e2163c6f106506dfb9b07dde67a24bfb90da65c661110cf2c5c6f71185754ee5ae3fd83a5465c92f72abd888b03187229da29"