aboutsummaryrefslogtreecommitdiff
path: root/Tools/Hazel-Networking/Hazel/Crypto/Sha256Stream.cs
blob: 19036936d42988cf092653b007da554afa65356c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Security.Cryptography;

namespace Hazel.Crypto
{
    /// <summary>
    /// Streams data into a SHA256 digest
    /// </summary>
    public class Sha256Stream : IDisposable
    {
        /// <summary>
        /// Size of the SHA256 digest in bytes
        /// </summary>
        public const int DigestSize = 32;

        private SHA256 hash = SHA256.Create();
        private bool isHashFinished = false;

        struct EmptyArray
        {
            public static readonly byte[] Value = new byte[0];
        }

        /// <summary>
        /// Create a new instance of a SHA256 stream
        /// </summary>
        public Sha256Stream()
        {
        }

        /// <summary>
        /// Release resources associated with the stream
        /// </summary>
        public void Dispose()
        {
            this.hash?.Dispose();
            this.hash = null;

            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Reset the stream to its initial state
        /// </summary>
        public void Reset()
        {
            this.hash?.Dispose();
            this.hash = SHA256.Create();
            this.isHashFinished = false;
        }

        /// <summary>
        /// Add data to the stream
        /// </summary>
        public void AddData(ByteSpan data)
        {
            while (data.Length > 0)
            {
                int offset = this.hash.TransformBlock(data.GetUnderlyingArray(), data.Offset, data.Length, null, 0);
                data = data.Slice(offset);
            }
        }

        /// <summary>
        /// Calculate the final hash of the stream data
        /// </summary>
        /// <param name="output">
        /// Target span to which the hash will be written
        /// </param>
        public void CopyOrCalculateFinalHash(ByteSpan output)
        {
            if (output.Length != DigestSize)
            {
                throw new ArgumentException($"Expected a span of {DigestSize} bytes. Got a span of {output.Length} bytes", nameof(output));
            }

            if (this.isHashFinished == false)
            {
                this.hash.TransformFinalBlock(EmptyArray.Value, 0, 0);
                this.isHashFinished = true;
            }

            new ByteSpan(this.hash.Hash).CopyTo(output);
        }
    }
}