public override void SetHash(byte[] content) { if (Hash is null) { KeccakManaged keccak = new KeccakManaged(512); List <string> entitesHashes = new List <string>(); foreach (var e in Entities) { entitesHashes.Add(e.GetHash()); } List <byte> buffer = new List <byte>(); foreach (var eh in entitesHashes) { buffer.AddRange(Encoding.UTF8.GetBytes(eh)); } var buf = keccak.ComputeHash(buffer.ToArray()); StringBuilder sb = new StringBuilder(); foreach (var b in buf) { sb.Append(b.ToString("X2")); } Hash = sb.ToString(); } else { throw new AccessViolationException("Hash can only be set once"); } }
/// <summary> /// Creates and set hash for file instance. /// </summary> /// <param name="content"> /// Raw bytes of file if needed in byte array. /// Only needed for <see cref="File.IsSingleBlock">Single Blocked files</see>. /// </param> /// <remarks> /// It would be better if hash was created during the upload, /// but it impossible, due to nature of this library and purposes. /// So, the best approach is to upload a file to IPFS, retrieve it and set content manually. /// </remarks> /// <exception cref="Exception"/> public void SetHash(byte[] content) { if (Hash is null) { KeccakManaged keccak = new KeccakManaged(512); if (this.IsSingleBlock) { if (content == null) { throw new ArgumentException("This file is single block and must be provided with byte array of content", "content"); } else { var buf = keccak.ComputeHash(content); StringBuilder sb = new StringBuilder(); foreach (var b in buf) { sb.Append(b.ToString("X2")); } Hash = sb.ToString(); } } else { List <string> blockHashes = new List <string>(); foreach (var b in Blocks) { blockHashes.Add(b.Hash); } List <byte> buffer = new List <byte>(); foreach (var bh in blockHashes) { buffer.AddRange(Encoding.UTF8.GetBytes(bh)); } var buf = keccak.ComputeHash(buffer.ToArray()); StringBuilder sb = new StringBuilder(); foreach (var b in buf) { sb.Append(b.ToString("X2")); } Hash = sb.ToString(); } } else { throw new AccessViolationException("Hash can only be set once"); } }
/// <summary> /// Creates and set hash for block instance. /// </summary> /// <param name="content"> /// Raw bytes of block in byte array. /// </param> /// <remarks> /// It would be better if block was creating it own hash during the upload, /// but it impossible, due to nature of this library and purposes. /// So, the best approach is to upload a file to IPFS, retrieve block and set it manually. /// </remarks> public void SetHash(byte[] content) { if (Hash is null) { KeccakManaged keccak = new KeccakManaged(512); var buf = keccak.ComputeHash(content); StringBuilder sb = new StringBuilder(); foreach (var b in buf) { sb.Append(b.ToString("X2")); } Hash = sb.ToString(); } else { throw new AccessViolationException("Hash can only be set once"); } }