/// <summary> /// Returns data hashed with provided algorithm. /// </summary> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <returns>Byte array containing hash of data.</returns> /// <exception cref="TimestampException"> /// Invalid digest length for given algorithm /// </exception> public byte[] GetHashedData(HashAlgorithm hashAlgorithm) { System.Security.Cryptography.HashAlgorithm algorithm = System.Security.Cryptography.HashAlgorithm.Create(hashAlgorithm.ToString()); switch (mode) { case DataMode.DATA_1: return(algorithm.ComputeHash(data)); case DataMode.STREAM_1: return(algorithm.ComputeHash(stream)); case DataMode.PATH_1: try { return(algorithm.ComputeHash(File.OpenRead(pathToFile))); } catch (Exception e) { throw new TimestampException("Can't calculate message digest from file: " + pathToFile, e); } case DataMode.HASHED_1: if (digest.Length != hashAlgorithm.GetLength()) { throw new TimestampException("Invalid digest length for given algorithm"); } return(digest); case DataMode.DATA_N: for (int i = 0; i < datas.Length - 1; i++) { algorithm.TransformBlock(datas[i], 0, datas[i].Length, datas[i], 0); } algorithm.TransformFinalBlock(datas[datas.Length - 1], 0, datas[datas.Length - 1].Length); return(algorithm.Hash); case DataMode.STREAM_N: using (MemoryStream finalStream = new MemoryStream()) { foreach (Stream stream in streams) { stream.CopyTo(finalStream); } return(algorithm.ComputeHash(finalStream.ToArray())); } case DataMode.PATH_N: int numberOfFiles = pathsToFiles.Length; for (int i = 0; i < numberOfFiles - 1; i++) { try { byte[] currentData = File.ReadAllBytes(pathsToFiles[i]); algorithm.TransformBlock(currentData, 0, currentData.Length, currentData, 0); } catch (Exception e) { throw new TimestampException("Can't calculate message digest from file: " + pathsToFiles[i], e); } } try { byte[] lastData = File.ReadAllBytes(pathsToFiles[numberOfFiles - 1]); algorithm.TransformFinalBlock(lastData, 0, lastData.Length); return(algorithm.Hash); } catch (Exception e) { throw new TimestampException("Can't calculate message digest from file: " + pathsToFiles[numberOfFiles - 1], e); } case DataMode.HASHED_N: int algorithmLength = hashAlgorithm.GetLength(); for (int i = 0; i < digests.Length - 1; i++) { algorithm.TransformBlock(digests[i], 0, digests[i].Length, digests[i], 0); } algorithm.TransformFinalBlock(digests[digests.Length - 1], 0, digests[digests.Length - 1].Length); return(algorithm.Hash); } return(null); }