2015-09-14 65 views
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) { 

} 

上述的Java代码是关于 “SHA1消息摘要”,并且有一个控制来限制数据大小:sha1.ComputeHash(FILESTREAM)

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); 
} 

回答

0

您可以使用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; 
}