1. 程式人生 > >MD5訊息摘要的java實現

MD5訊息摘要的java實現

今天這個程式就是從檔案中讀取訊息,使用MD5進行訊息摘要

直接上程式:

package function;
import java.util.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.security.*;
import javax.crypto.*;

public class MDF {
	String algorithm = "MD5";
	
	public void getInfo(String infile,String outfile){
		try{
			MessageDigest md = MessageDigest.getInstance(algorithm);
			BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));
			String mes = "";
			StringBuffer buff = new StringBuffer();
			while((mes=reader.readLine())!=null){
				buff.append(mes);
			}
			reader.close();
			mes=buff.toString();
			md.update(mes.getBytes());
			
			FileOutputStream out = new FileOutputStream(new File(outfile));
			out.write(convertToHex(md.digest()).getBytes());
			out.close();
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public String convertToHex(byte[] info){
		StringBuffer buf = new StringBuffer();
		for(byte count : info){
			String t = Integer.toHexString(0xff & count);
			if(t.length() == 1)
				buf.append("0"+t);
			else
				buf.append(t);
		}
		return  buf.toString();
	}
	
	public static void main(String[] args){
		String infile,outfile;
		System.out.println("input the original file name");
		Scanner scan = new Scanner(System.in);
		infile=scan.nextLine();
		System.out.println("input the doc name of the result");
		outfile = scan.nextLine();
		MDF md = new MDF();
		md.getInfo(infile, outfile);
		System.out.println("program finished");
	}
}