Use BouncyCastle hashing functions
[NovacoinLibrary.git] / Novacoin / Hash.cs
1 \feff/**
2  *  Novacoin classes library
3  *  Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
4
5  *  This program is free software: you can redistribute it and/or modify
6  *  it under the terms of the GNU Affero General Public License as
7  *  published by the Free Software Foundation, either version 3 of the
8  *  License, or (at your option) any later version.
9
10  *  This program is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  *  GNU Affero General Public License for more details.
14
15  *  You should have received a copy of the GNU Affero General Public License
16  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 using System;
20 using System.Linq;
21
22 namespace Novacoin
23 {
24     public abstract class Hash
25     {
26         /// <summary>
27         /// Array of digest bytes.
28         /// </summary>
29         protected byte[] _hashBytes = null;
30
31         /// <summary>
32         /// Hash size, must be overriden
33         /// </summary>
34         public abstract int hashSize 
35         {
36             get; 
37         }
38
39         public byte[] hashBytes
40         {
41             get { return _hashBytes; }
42         }
43
44         /// <summary>
45         /// Initializes an empty instance of the Hash class.
46         /// </summary>
47         public Hash()
48         {
49             _hashBytes = new byte[hashSize];
50         }
51
52         /// <summary>
53         /// Initializes a new instance of Hash class
54         /// </summary>
55         /// <param name="bytesList">Array of bytes</param>
56         public Hash(byte[] bytes, int offset = 0)
57         {
58             _hashBytes = new byte[hashSize];
59             Array.Copy(bytes, offset, _hashBytes, 0, hashSize);
60         }
61
62         /// <summary>
63         /// Initializes a new instance of Hash class as a copy of another one
64         /// </summary>
65         /// <param name="bytesList">Instance of hash class</param>
66         public Hash(Hash h)
67         {
68             _hashBytes = new byte[h.hashSize];
69             h._hashBytes.CopyTo(_hashBytes, 0);
70         }
71
72         public bool IsZero
73         {
74             get { return !_hashBytes.Any(b => b != 0); }
75         }
76
77         /*public static implicit operator BigInteger(Hash h)
78         {
79             return new BigInteger(h._hashBytes);
80         }*/
81
82         public override string ToString()
83         {
84             return Interop.ToHex(Interop.ReverseBytes(_hashBytes));
85         }
86     }
87 }