JAVA用OPENSSL计算文件的SHA1值,并以BASE64格式保存

来源:互联网 发布:keepalived 算法 编辑:程序博客网 时间:2024/05/21 17:02
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import sun.misc.BASE64Encoder;

public class MDCalculationTest {

    
public MDCalculationTest(String fileName) {
        FileInputStream fis 
= null;
        BufferedInputStream bufferedInputStream 
= null;
        
try {
System.out.println(
"programing begin....");
SimpleDateFormat df 
= new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(df.format(
new Date()));
            MessageDigest alga 
= MessageDigest.getInstance("SHA-1");

            File file 
= new File(fileName);
            
if (!file.exists() || file.isDirectory()) {
                
throw new FileNotFoundException("file is not exsit!");
            }

    
            fis 
= new FileInputStream(file);
            bufferedInputStream 
= new BufferedInputStream(fis);
            
byte[] bt = new byte[4096];
            
int tmp = 0;
            
while (true{
                tmp 
= bufferedInputStream.read(bt, 0, bt.length);                
                
if (tmp < 0{
                    
break;
                }


                Thread.yield();
                alga.update(bt, 
0, tmp);
            }

            
            
byte[] digesta = alga.digest();            
            BASE64Encoder base64 
= new BASE64Encoder();
            String result 
= base64.encode(digesta);
System.out.println(
"base64 encode's result is = " + result);
System.out.println(df.format(
new Date()));
        }
 catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
 catch (FileNotFoundException e) {
            e.printStackTrace();
        }
 catch (IOException e) {
            e.printStackTrace();
        }
 finally {
            
if (bufferedInputStream != null{
            
try {
                bufferedInputStream.close();
            }
 catch (IOException e) {
                e.printStackTrace();
            }

            }

        }

    }

    
    
public static void main(String args[]) {
        
if (args == null || args.length == 0{
            System.out.println(
"please input the fullpath of an file. then excute again!");
            
return;
        }

        MDCalculationTest test 
= new MDCalculationTest(args[0]);
    }

}

 
原创粉丝点击