0
/// <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) {

}

The java codes above is about "Sha1 MessageDigest", and there is a control to limit data size:

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

If i use c# api, how to limit the data size? What's more, I just know:

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

byte[] result;

using (FileStream fs = new FileStream("filename", FileMode.Open))
{
    result = sha1.ComputeHash(fs);
}   
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
陈黎栋John
  • 175
  • 1
  • 9

1 Answers1

0

You can use TransformBlock and TransformFinalBlock methods to limit the size.

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;
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65