sha1.ComputeHash(文件流)

sha1.ComputeHash(fileStream)

/// <summary>
/// 读取指定文件块数据Sha1
/// </summary>
/// <param name="fis">
/// @return </param>
private static MessageDigest calSha1(BufferedInputStream fis) {
    MessageDigest sha1 = null;
    try {
        byte[] buffer = new byte[1024];
        int numRead = 0;
        int total = 0;
        sha1 = MessageDigest.getInstance("SHA-1");
        while ((numRead = fis.read(buffer)) > 0) {
            sha1.update(buffer, 0, numRead);
            total += numRead;
            if (total >= BLOCK_SIZE) {
                break;
            }
        }
    } catch (Exception e) {

}

上面的java代码是关于"Sha1 MessageDigest"的,还有一个限制数据大小的控件:

if (total >= BLOCK_SIZE) {//每次最多读入4M
    break;
}

如果我使用c# api,如何限制数据大小?更何况,我只知道:

HashAlgorithm sha1 = HashAlgorithm.Create("sha1");

byte[] result;

using (FileStream fs = new FileStream("filename", FileMode.Open))
{
    result = sha1.ComputeHash(fs);
}   

您可以使用TransformBlockTransformFinalBlock方法来限制大小。

public static byte[] GetPartialHash(byte[] input, int size)
{
    var sha = new SHA1Managed();
    int offset = 0;

    while (input.Length - offset >= size)
        offset += sha.TransformBlock(input, offset, size, input, offset);

    sha.TransformFinalBlock(input, offset, input.Length - offset);
    return sha.Hash;
}