public void SetChecksum(byte[] block, int offset, int length) { var byteToProcess = new byte[length]; Array.Copy(block, offset, byteToProcess, 0, length); _checksum = ZsyncUtil.Md4Hash(byteToProcess); }
public static List <BlockSum> GenerateBlocksum(byte[] input, int weakLength, int strongLength, int blockSize) { using (var stream = new MemoryStream(input)) { int capacity = ((int)(input.Length / blockSize) + (input.Length % blockSize > 0 ? 1 : 0)) * (weakLength + strongLength) + 20; List <BlockSum> blockSums = new List <BlockSum>(); var weakbytesMs = new MemoryStream(4); int count = 0; byte[] block = new byte[blockSize]; int read; while ((read = stream.Read(block, 0, block.Length)) != 0) { if (read < blockSize) { // Pad with 0's block = Pad(block, read, blockSize, 0); } //weakbytesMs.Clear(); weakbytesMs.SetLength(0); weakbytesMs.SetLength(weakLength); var weakCheckSum = (ushort)ZsyncUtil.ComputeRsum(block); weakbytesMs.Position = weakbytesMs.Length - weakLength; var strongbytesMs = new MemoryStream(ZsyncUtil.Md4Hash(block.ToArray())); strongbytesMs.SetLength(strongLength); byte[] strongBytesBuffer = new byte[strongLength]; strongbytesMs.Read(strongBytesBuffer, 0, strongLength); blockSums.Add(new BlockSum(weakCheckSum, strongBytesBuffer, count)); count++; } return(blockSums); } }
private static (byte[] checksums, byte[] sha1) ComputeCheckSums(FileInfo file, int blockSize, long fileLength, int weakLength, int strongLength) { /* * As per the zsync spec, a weak checksum is md4 and a strong checksum is sha1 */ int capacity = ((int)(fileLength / blockSize) + (fileLength % blockSize > 0 ? 1 : 0)) * (weakLength + strongLength) + 20; // 20 = SHA1 length /* * CheckSums * WeakBytes * * Limit = Length */ var checkSumsMs = new MemoryStream(capacity); var weakbytesMs = new MemoryStream(weakLength); byte[] block = new byte[blockSize]; using (BufferedStream stream = new BufferedStream(new FileStream(file.FullName, FileMode.Open, FileAccess.Read), 1000000)) { int read; while ((read = stream.Read(block, 0, block.Length)) != 0) { if (read < blockSize) { // Pad with 0's block = Pad(block, read, blockSize, 0); } //weakbytesMs.Clear(); weakbytesMs.SetLength(0); weakbytesMs.SetLength(weakLength); var weakCheckSum = (ushort)ZsyncUtil.ComputeRsum(block); //weakbytesMs.Position = weakbytesMs.Length - weakLength; Write(checkSumsMs, MiscUtil.Conversion.EndianBitConverter.Big.GetBytes(weakCheckSum)); var strongbytesMs = new MemoryStream(ZsyncUtil.Md4Hash(block.ToArray())); strongbytesMs.SetLength(strongLength); byte[] strongBytesBuffer = new byte[strongLength]; strongbytesMs.Read(strongBytesBuffer, 0, strongLength); checkSumsMs.Write(strongBytesBuffer, 0, strongLength); } stream.Seek(0, SeekOrigin.Begin); var cryptoProvider = new SHA1CryptoServiceProvider(); var fileHash = cryptoProvider.ComputeHash(stream); return(checkSumsMs.ToArray(), fileHash); } }