Java:如何为文件创建SHA-1? [英] Java: How to create SHA-1 for a file?

查看:145
本文介绍了Java:如何为文件创建SHA-1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在纯Java6中为非常大的文件创建SHA-1的最佳方法是什么?如何实现此方法:

What is the best way to create a SHA-1 for a very large file in pure Java6? How to implement this method:

public abstract String createSha1(java.io.File file);


推荐答案

使用 MessageDigest 类和提供数据一块一块。下面的例子忽略了将byte []转换为字符串并关闭文件的细节,但应该给出一般的想法。

Use the MessageDigest class and supply data piece by piece. The example below ignores details like turning byte[] into string and closing the file, but should give you the general idea.

public byte[] createSha1(File file) throws Exception  {
    MessageDigest digest = MessageDigest.getInstance("SHA-1");
    InputStream fis = new FileInputStream(file);
    int n = 0;
    byte[] buffer = new byte[8192];
    while (n != -1) {
        n = fis.read(buffer);
        if (n > 0) {
            digest.update(buffer, 0, n);
        }
    }
    return digest.digest();
}

这篇关于Java:如何为文件创建SHA-1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆