e013e8ba414dafc8d904577f8d18933aaafb477c
[NovacoinLibrary.git] / Novacoin / Hash.cs
1 \feffusing System.Security.Cryptography;
2 using System.Collections.Generic;
3 using System.Linq;
4
5 namespace Novacoin
6 {
7     public abstract class Hash
8     {
9         /// <summary>
10         /// Computes the SHA256 hash for the input data using the managed library.
11         /// </summary>
12         protected static SHA256Managed _hasher256 = new SHA256Managed();
13         
14         /// <summary>
15         /// Array of digest bytes.
16         /// </summary>
17         protected byte[] _hashBytes = null;
18
19         /// <summary>
20         /// Hash size, must be overriden
21         /// </summary>
22         public abstract int hashSize 
23         {
24             get; 
25         }
26
27         public byte[] hashBytes
28         {
29             get { return _hashBytes; }
30         }
31
32         /// <summary>
33         /// Initializes an empty instance of the Hash class.
34         /// </summary>
35         public Hash()
36         {
37             _hashBytes = Enumerable.Repeat<byte>(0, hashSize).ToArray();
38         }
39
40         /// <summary>
41         /// Initializes a new instance of Hash class with first 20 bytes from supplied list
42         /// </summary>
43         /// <param name="bytesList">List of bytes</param>
44         public Hash(IEnumerable<byte> bytes)
45         {
46             _hashBytes = bytes.Take(hashSize).ToArray();
47         }
48
49         public Hash(byte[] bytes)
50         {
51             _hashBytes = bytes;
52         }
53
54         public Hash(Hash h)
55         {
56             _hashBytes = new byte[h.hashSize];
57             h._hashBytes.CopyTo(_hashBytes, 0);
58         }
59
60         public bool IsZero
61         {
62             get { return !_hashBytes.Any(b => b != 0); }
63         }
64
65         public override string ToString()
66         {
67             return Interop.ToHex(Interop.ReverseBytes(_hashBytes));
68         }
69     }
70 }