MD5加密的实现

MD5(Message-Digest Algorithm 5)的典型应用是对一段信息(Message)产生信息摘要(Message-Digest),以防止被篡改。

一、将文件通过流的方式转化为二进制,再计算该文件的MD5值。在实际运用中,加密和解密的方法最好一样。

package zju.give.util;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

//和MES统一的MD5方法
public class MD5toHex {
	//MD5值校验用    toHex方法
		public static String toHex(byte[] bytes) {
			final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
			StringBuilder ret = new StringBuilder(bytes.length*2);
			for(int i=0; i<bytes.length; i++){
				ret.append(HEX_DIGITS[(bytes[i] >>4) & 0x0f]);
				ret.append(HEX_DIGITS[bytes[i] & 0x0f]);	
			}
			return ret.toString();
		}
		
		//测试MD5
		public static void main(String[] args) {
			
			byte[] bytes = null;
			try {
				FileInputStream in = new FileInputStream("D:\\test3.txt");
				BufferedInputStream is = new BufferedInputStream(in);
				bytes = new byte[in.available()];
				int len = in.available();
				int offset = 0;
				int read = 0;
				while (offset < len && (read = is.read(bytes, offset, len - offset)) >= 0) {
					offset += read;
				}
				is.close();
				in.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			//文件内容必须根据原始的文件二进制进行转换
			String fileComment = new String(new sun.misc.BASE64Encoder().encodeBuffer(bytes));
			System.out.println(fileComment);
			
			try {
				MessageDigest md5New = MessageDigest.getInstance("MD5");
				bytes = md5New.digest(bytes);
			} catch (NoSuchAlgorithmException e) { 
				e.printStackTrace();
			}
			String md = MD5toHex.toHex(bytes);
			System.out.println(md);
		}
}



猜你喜欢

转载自blog.csdn.net/pcwl1206/article/details/80598747