Java 读取文件 MD5 sha1 sha256 sha224 sha384 sha512

在Java中读取文件的MD5或SHA码,用于对文件完整性进行校验,示例代码较为简单,如下:
一、使用到的 jar (pom.xml)

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.14</version>
</dependency>

二、代码示例

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;

public class TestSHA {

	    public static String getSHA1(String filePath) {
	        try {
				File file = new File(filePath);
				FileInputStream fileInputStream = new FileInputStream(file);
				String hex = DigestUtils.sha1Hex(fileInputStream);
				return hex;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	        return null;
	    }
	    
	    public static String getSHA(String filePath, String messageDigestAlgorithms) {
	    	String hex = null;
			try {
				File file = new File(filePath);
				hex = new DigestUtils(messageDigestAlgorithms).digestAsHex(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return hex;
	    }
	    
	    public static void main(String[] args) {
//	    	MessageDigestAlgorithms.SHA_1
	    	String filePath = "D:\\apache\\apache-maven\\repository\\commons-lang\\commons-lang\\2.6\\commons-lang-2.6.jar";// 0ce1edb914c94ebc388f086c6827e8bdeec71ac2
	    	System.out.println(getSHA1(filePath));
	    	System.out.println(getSHA(filePath, MessageDigestAlgorithms.SHA_1));
		}
	    
}

(END)

猜你喜欢

转载自blog.csdn.net/catoop/article/details/104669980
今日推荐