summary refs log tree commit diff
path: root/crypto/src/crypto/generators/BaseKdfBytesGenerator.cs
blob: a1839dc3388847418b5555d81b48896cb543f67f (plain) (blame)
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
using System;

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Utilities;

namespace Org.BouncyCastle.Crypto.Generators
{
    /**
    * Basic KDF generator for derived keys and ivs as defined by IEEE P1363a/ISO 18033
    * <br/>
    * This implementation is based on ISO 18033/P1363a.
    */
    public abstract class BaseKdfBytesGenerator
        : IDerivationFunction
    {
        private int     counterStart;
        private IDigest  digest;
        private byte[]  shared;
        private byte[]  iv;

        /**
        * Construct a KDF Parameters generator.
        *
        * @param counterStart value of counter.
        * @param digest the digest to be used as the source of derived keys.
        */
        protected BaseKdfBytesGenerator(int counterStart, IDigest digest)
        {
            this.counterStart = counterStart;
            this.digest = digest;
        }

        public void Init(IDerivationParameters parameters)
        {
            if (parameters is KdfParameters kdfParameters)
            {
                shared = kdfParameters.GetSharedSecret();
                iv = kdfParameters.GetIV();
            }
            else if (parameters is Iso18033KdfParameters iso18033KdfParameters)
            {
                shared = iso18033KdfParameters.GetSeed();
                iv = null;
            }
            else
            {
                throw new ArgumentException("KDF parameters required for KDF Generator");
            }
        }

        /**
        * return the underlying digest.
        */
        public IDigest Digest => digest;

        /**
        * fill len bytes of the output buffer with bytes generated from
        * the derivation function.
        *
        * @throws ArgumentException if the size of the request will cause an overflow.
        * @throws DataLengthException if the out buffer is too small.
        */
        public int GenerateBytes(byte[] output, int outOff, int length)
        {
            Check.OutputLength(output, outOff, length, "output buffer too small");

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            return GenerateBytes(output.AsSpan(outOff, length));
#else
            long oBytes = length;
            int digestSize = digest.GetDigestSize();

            //
            // this is at odds with the standard implementation, the
            // maximum value should be hBits * (2^32 - 1) where hBits
            // is the digest output size in bits. We can't have an
            // array with a long index at the moment...
            //
            if (oBytes > ((2L << 32) - 1))
                throw new ArgumentException("Output length too large");

            int cThreshold = (int)((oBytes + digestSize - 1) / digestSize);

            byte[] dig = new byte[digestSize];

            byte[] C = new byte[4];
            Pack.UInt32_To_BE((uint)counterStart, C, 0);

            uint counterBase = (uint)(counterStart & ~0xFF);

            for (int i = 0; i < cThreshold; i++)
            {
                digest.BlockUpdate(shared, 0, shared.Length);
                digest.BlockUpdate(C, 0, 4);

                if (iv != null)
                {
                    digest.BlockUpdate(iv, 0, iv.Length);
                }

                digest.DoFinal(dig, 0);

                if (length > digestSize)
                {
                    Array.Copy(dig, 0, output, outOff, digestSize);
                    outOff += digestSize;
                    length -= digestSize;
                }
                else
                {
                    Array.Copy(dig, 0, output, outOff, length);
                }

                if (++C[3] == 0)
                {
                    counterBase += 0x100;
                    Pack.UInt32_To_BE(counterBase, C, 0);
                }
            }

            digest.Reset();

            return (int)oBytes;
#endif
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public int GenerateBytes(Span<byte> output)
        {
            long oBytes = output.Length;
            int digestSize = digest.GetDigestSize();

            //
            // this is at odds with the standard implementation, the
            // maximum value should be hBits * (2^32 - 1) where hBits
            // is the digest output size in bits. We can't have an
            // array with a long index at the moment...
            //
            if (oBytes > ((2L << 32) - 1))
                throw new ArgumentException("Output length too large");

            int cThreshold = (int)((oBytes + digestSize - 1) / digestSize);

            Span<byte> dig = digestSize <= 128
                ? stackalloc byte[digestSize]
                : new byte[digestSize];

            Span<byte> C = stackalloc byte[4];
            Pack.UInt32_To_BE((uint)counterStart, C);

            uint counterBase = (uint)(counterStart & ~0xFF);

            for (int i = 0; i < cThreshold; i++)
            {
                digest.BlockUpdate(shared);
                digest.BlockUpdate(C);

                if (iv != null)
                {
                    digest.BlockUpdate(iv);
                }

                digest.DoFinal(dig);

                int remaining = output.Length;
                if (remaining > digestSize)
                {
                    dig.CopyTo(output);
                    output = output[digestSize..];
                }
                else
                {
                    dig[..remaining].CopyTo(output);
                }

                if (++C[3] == 0)
                {
                    counterBase += 0x100;
                    Pack.UInt32_To_BE(counterBase, C);
                }
            }

            digest.Reset();

            return (int)oBytes;
        }
#endif
    }
}