summary refs log tree commit diff
path: root/crypto/src/crmf/PKMacBuilder.cs
blob: ae9baa3d0156d35390113ca60a89efbbae0384df (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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
using System;
using System.IO;

using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cmp;
using Org.BouncyCastle.Asn1.Iana;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Crmf
{
    internal class PKMacStreamCalculator
        : IStreamCalculator<DefaultPKMacResult>
    {
        private readonly MacSink _stream;

        public PKMacStreamCalculator(IMac mac)
        {
            _stream = new MacSink(mac);
        }

        public Stream Stream
        {
            get { return _stream; }
        }

        public DefaultPKMacResult GetResult()
        {
            return new DefaultPKMacResult(_stream.Mac);
        }
    }

    internal class PKMacFactory
        : IMacFactory
    {
        protected readonly PbmParameter parameters;
        private readonly byte[] key;

        public PKMacFactory(byte[] key, PbmParameter parameters)
        {
            this.key = Arrays.Clone(key);
            this.parameters = parameters;
        }

        public virtual object AlgorithmDetails
        {
            get { return new AlgorithmIdentifier(CmpObjectIdentifiers.passwordBasedMac, parameters); }
        }

        public virtual IStreamCalculator<IBlockResult> CreateCalculator()
        {
            IMac mac = MacUtilities.GetMac(parameters.Mac.Algorithm);
            mac.Init(new KeyParameter(key));
            return new PKMacStreamCalculator(mac);
        }
    }

    internal class DefaultPKMacResult
        : IBlockResult
    {
        private readonly IMac mac;

        public DefaultPKMacResult(IMac mac)
        {
            this.mac = mac;
        }

        public byte[] Collect()
        {
            byte[] res = new byte[mac.GetMacSize()];
            mac.DoFinal(res, 0);
            return res;
        }

        public int Collect(byte[] sig, int sigOff)
        {
            byte[] signature = Collect();
            signature.CopyTo(sig, sigOff);
            return signature.Length;
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        public int Collect(Span<byte> destination)
        {
            byte[] result = Collect();
            result.CopyTo(destination);
            return result.Length;
        }
#endif
    }

    public class PKMacBuilder
    {
        private AlgorithmIdentifier owf;
        private AlgorithmIdentifier mac;
        private IPKMacPrimitivesProvider provider;
        private SecureRandom random;
        private PbmParameter parameters;
        private int iterationCount;
        private int saltLength = 20;
        private int maxIterations;

        /// <summary>
        /// Default, IterationCount = 1000, OIW=IdSha1, Mac=HmacSHA1
        /// </summary>
        public PKMacBuilder() :
            this(new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1), 1000, new AlgorithmIdentifier(IanaObjectIdentifiers.HmacSha1, DerNull.Instance), new DefaultPKMacPrimitivesProvider())
        {
        }

        /// <summary>
        /// Defaults with IPKMacPrimitivesProvider
        /// </summary>
        /// <param name="provider"></param>
        public PKMacBuilder(IPKMacPrimitivesProvider provider) :
            this(new AlgorithmIdentifier(OiwObjectIdentifiers.IdSha1), 1000, new AlgorithmIdentifier(IanaObjectIdentifiers.HmacSha1, DerNull.Instance), provider)
        {
        }

        /// <summary>
        /// Create.
        /// </summary>
        /// <param name="provider">The Mac provider</param>
        /// <param name="digestAlgorithmIdentifier">Digest Algorithm Id</param>
        /// <param name="macAlgorithmIdentifier">Mac Algorithm Id</param>
        public PKMacBuilder(IPKMacPrimitivesProvider provider, AlgorithmIdentifier digestAlgorithmIdentifier, AlgorithmIdentifier macAlgorithmIdentifier) :
            this(digestAlgorithmIdentifier, 1000, macAlgorithmIdentifier, provider)
        {
        }

        /// <summary>
        /// Create a PKMAC builder enforcing a ceiling on the maximum iteration count.
        /// </summary>
        /// <param name="provider">supporting calculator</param>
        /// <param name="maxIterations">max allowable value for iteration count.</param>
        public PKMacBuilder(IPKMacPrimitivesProvider provider, int maxIterations)
        {
            this.provider = provider;
            this.maxIterations = maxIterations;
        }

        private PKMacBuilder(AlgorithmIdentifier digestAlgorithmIdentifier, int iterationCount, AlgorithmIdentifier macAlgorithmIdentifier, IPKMacPrimitivesProvider provider)
        {
            this.iterationCount = iterationCount;
            this.mac = macAlgorithmIdentifier;
            this.owf = digestAlgorithmIdentifier;
            this.provider = provider;
        }

        /**
         * Set the salt length in octets.
         *
         * @param saltLength length in octets of the salt to be generated.
         * @return the generator
         */
        public PKMacBuilder SetSaltLength(int saltLength)
        {
            if (saltLength < 8)
                throw new ArgumentException("salt length must be at least 8 bytes");

            this.saltLength = saltLength;

            return this;
        }

        /// <summary>
        /// Set the iteration count.
        /// </summary>
        /// <param name="iterationCount">the iteration count.</param>
        /// <returns>this</returns>
        /// <exception cref="ArgumentException">if iteration count is less than 100</exception>
        public PKMacBuilder SetIterationCount(int iterationCount)
        {
            if (iterationCount < 100)
                throw new ArgumentException("iteration count must be at least 100");

            CheckIterationCountCeiling(iterationCount);

            this.iterationCount = iterationCount;

            return this;
        }

        /// <summary>
        /// Set PbmParameters
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>this</returns>
        public PKMacBuilder SetParameters(PbmParameter parameters)
        {
            CheckIterationCountCeiling(parameters.IterationCount.IntValueExact);

            this.parameters = parameters;

            return this;
        }

        /// <summary>
        /// The Secure random
        /// </summary>
        /// <param name="random">The random.</param>
        /// <returns>this</returns>
        public PKMacBuilder SetSecureRandom(SecureRandom random)
        {
            this.random = random;

            return this;
        }

        /// <summary>
        /// Build an IMacFactory.
        /// </summary>
        /// <param name="password">The password.</param>
        /// <returns>IMacFactory</returns>
        public IMacFactory Build(char[] password)
        {
            if (parameters != null)
                return GenCalculator(parameters, password);

            byte[] salt = new byte[saltLength];

            this.random = CryptoServicesRegistrar.GetSecureRandom(random);

            random.NextBytes(salt);

            return GenCalculator(new PbmParameter(salt, owf, iterationCount, mac), password);
        }

        private void CheckIterationCountCeiling(int iterationCount)
        {
            if (maxIterations > 0 && iterationCount > maxIterations)
                throw new ArgumentException("iteration count exceeds limit (" + iterationCount + " > " + maxIterations + ")");
        }

        private IMacFactory GenCalculator(PbmParameter parameters, char[] password)
        {
            // From RFC 4211
            //
            //   1.  Generate a random salt value S
            //
            //   2.  Append the salt to the pw.  K = pw || salt.
            //
            //   3.  Hash the value of K.  K = HASH(K)
            //
            //   4.  Iter = Iter - 1.  If Iter is greater than zero.  Goto step 3.
            //
            //   5.  Compute an HMAC as documented in [HMAC].
            //
            //       MAC = HASH( K XOR opad, HASH( K XOR ipad, data) )
            //
            //       Where opad and ipad are defined in [HMAC].
            byte[] pw = Strings.ToUtf8ByteArray(password);
            byte[] salt = parameters.Salt.GetOctets();
            byte[] K = new byte[pw.Length + salt.Length];

            Array.Copy(pw, 0, K, 0, pw.Length);
            Array.Copy(salt, 0, K, pw.Length, salt.Length);

            IDigest digest = provider.CreateDigest(parameters.Owf);

            int iter = parameters.IterationCount.IntValueExact;

            digest.BlockUpdate(K, 0, K.Length);

            K = new byte[digest.GetDigestSize()];

            digest.DoFinal(K, 0);

            while (--iter > 0)
            {
                digest.BlockUpdate(K, 0, K.Length);

                digest.DoFinal(K, 0);
            }

            byte[] key = K;

            return new PKMacFactory(key, parameters);
        }
    }
}