summary refs log tree commit diff
path: root/crypto/src/crypto/signers/Iso9796d2PssSigner.cs
blob: 1486656bdebefddebfd9aa5ed22bf5afecac82c3 (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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
using System;
using System.Collections;

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

namespace Org.BouncyCastle.Crypto.Signers
{
    /// <summary> ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3).
    /// <p>
    /// Note: the usual length for the salt is the length of the hash
    /// function used in bytes.</p>
    /// </summary>
    public class Iso9796d2PssSigner
        : ISignerWithRecovery
    {
        /// <summary>
        /// Return a reference to the recoveredMessage message.
        /// </summary>
        /// <returns>The full/partial recoveredMessage message.</returns>
        /// <seealso cref="ISignerWithRecovery.GetRecoveredMessage"/>
        public byte[] GetRecoveredMessage()
        {
            return recoveredMessage;
        }

        public const int TrailerImplicit = 0xBC;
        public const int TrailerRipeMD160 = 0x31CC;
        public const int TrailerRipeMD128 = 0x32CC;
        public const int TrailerSha1 = 0x33CC;
        public const int TrailerSha256 = 0x34CC;
        public const int TrailerSha512 = 0x35CC;
        public const int TrailerSha384 = 0x36CC;
        public const int TrailerWhirlpool = 0x37CC;

        private static readonly IDictionary trailerMap = Platform.CreateHashtable();

        static Iso9796d2PssSigner()
        {
            trailerMap.Add("RIPEMD128", TrailerRipeMD128);
            trailerMap.Add("RIPEMD160", TrailerRipeMD160);
            trailerMap.Add("SHA-1", TrailerSha1);
            trailerMap.Add("SHA-256", TrailerSha256);
            trailerMap.Add("SHA-384", TrailerSha384);
            trailerMap.Add("SHA-512", TrailerSha512);

            trailerMap.Add("Whirlpool", TrailerWhirlpool);
        }

        private IDigest digest;
        private IAsymmetricBlockCipher cipher;

        private SecureRandom random;
        private byte[] standardSalt;

        private int hLen;
        private int trailer;
        private int keyBits;
        private byte[] block;
        private byte[] mBuf;
        private int messageLength;
        private readonly int saltLength;
        private bool fullMessage;
        private byte[] recoveredMessage;

        private byte[] preSig;
        private byte[] preBlock;
        private int preMStart;
        private int preTLength;

        /// <summary>
        /// Generate a signer for the with either implicit or explicit trailers
        /// for ISO9796-2, scheme 2 or 3.
        /// </summary>
        /// <param name="cipher">base cipher to use for signature creation/verification</param>
        /// <param name="digest">digest to use.</param>
        /// <param name="saltLength">length of salt in bytes.</param>
        /// <param name="isImplicit">whether or not the trailer is implicit or gives the hash.</param>
        public Iso9796d2PssSigner(
            IAsymmetricBlockCipher	cipher,
            IDigest					digest,
            int						saltLength,
            bool					isImplicit)
        {
            this.cipher = cipher;
            this.digest = digest;
            this.hLen = digest.GetDigestSize();
            this.saltLength = saltLength;

            if (isImplicit)
            {
                trailer = TrailerImplicit;
            }
            else
            {
                string digestAlg = digest.AlgorithmName;
                if (!trailerMap.Contains(digestAlg))
                    throw new ArgumentException("no valid trailer for digest");

                trailer = (int)trailerMap[digestAlg];
            }
        }

        /// <summary> Constructor for a signer with an explicit digest trailer.
        ///
        /// </summary>
        /// <param name="cipher">cipher to use.
        /// </param>
        /// <param name="digest">digest to sign with.
        /// </param>
        /// <param name="saltLength">length of salt in bytes.
        /// </param>
        public Iso9796d2PssSigner(
            IAsymmetricBlockCipher	cipher,
            IDigest					digest,
            int						saltLength)
            : this(cipher, digest, saltLength, false)
        {
        }

        public virtual string AlgorithmName
        {
            get { return digest.AlgorithmName + "with" + "ISO9796-2S2"; }
        }

        /// <summary>Initialise the signer.</summary>
        /// <param name="forSigning">true if for signing, false if for verification.</param>
        /// <param name="parameters">parameters for signature generation/verification. If the
        /// parameters are for generation they should be a ParametersWithRandom,
        /// a ParametersWithSalt, or just an RsaKeyParameters object. If RsaKeyParameters
        /// are passed in a SecureRandom will be created.
        /// </param>
        /// <exception cref="ArgumentException">if wrong parameter type or a fixed
        /// salt is passed in which is the wrong length.
        /// </exception>
        public virtual void Init(
            bool				forSigning,
            ICipherParameters	parameters)
        {
            RsaKeyParameters kParam;
            if (parameters is ParametersWithRandom)
            {
                ParametersWithRandom p = (ParametersWithRandom) parameters;

                kParam = (RsaKeyParameters) p.Parameters;

                if (forSigning)
                {
                    random = p.Random;
                }
            }
            else if (parameters is ParametersWithSalt)
            {
                if (!forSigning)
                    throw new ArgumentException("ParametersWithSalt only valid for signing", "parameters");

                ParametersWithSalt p = (ParametersWithSalt) parameters;

                kParam = (RsaKeyParameters) p.Parameters;
                standardSalt = p.GetSalt();

                if (standardSalt.Length != saltLength)
                    throw new ArgumentException("Fixed salt is of wrong length");
            }
            else
            {
                kParam = (RsaKeyParameters) parameters;

                if (forSigning)
                {
                    random = new SecureRandom();
                }
            }

            cipher.Init(forSigning, kParam);

            keyBits = kParam.Modulus.BitLength;

            block = new byte[(keyBits + 7) / 8];

            if (trailer == TrailerImplicit)
            {
                mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 1];
            }
            else
            {
                mBuf = new byte[block.Length - digest.GetDigestSize() - saltLength - 1 - 2];
            }

            Reset();
        }

        /// <summary> compare two byte arrays - constant time.</summary>
        private bool IsSameAs(byte[] a, byte[] b)
        {
            if (messageLength != b.Length)
            {
                return false;
            }

            bool isOkay = true;

            for (int i = 0; i != b.Length; i++)
            {
                if (a[i] != b[i])
                {
                    isOkay = false;
                }
            }

            return isOkay;
        }

        /// <summary> clear possible sensitive data</summary>
        private void  ClearBlock(
            byte[] block)
        {
            Array.Clear(block, 0, block.Length);
        }

        public virtual void UpdateWithRecoveredMessage(
            byte[] signature)
        {
            byte[] block = cipher.ProcessBlock(signature, 0, signature.Length);

            //
            // adjust block size for leading zeroes if necessary
            //
            if (block.Length < (keyBits + 7) / 8)
            {
                byte[] tmp = new byte[(keyBits + 7) / 8];

                Array.Copy(block, 0, tmp, tmp.Length - block.Length, block.Length);
                ClearBlock(block);
                block = tmp;
            }

            int tLength;

            if (((block[block.Length - 1] & 0xFF) ^ 0xBC) == 0)
            {
                tLength = 1;
            }
            else
            {
                int sigTrail = ((block[block.Length - 2] & 0xFF) << 8) | (block[block.Length - 1] & 0xFF);

                string digestAlg = digest.AlgorithmName;
                if (!trailerMap.Contains(digestAlg))
                    throw new ArgumentException("unrecognised hash in signature");

                if (sigTrail != (int)trailerMap[digestAlg])
                    throw new InvalidOperationException("signer initialised with wrong digest for trailer " + sigTrail);

                tLength = 2;
            }

            //
            // calculate H(m2)
            //
            byte[] m2Hash = new byte[hLen];
            digest.DoFinal(m2Hash, 0);

            //
            // remove the mask
            //
            byte[] dbMask = MaskGeneratorFunction1(block, block.Length - hLen - tLength, hLen, block.Length - hLen - tLength);
            for (int i = 0; i != dbMask.Length; i++)
            {
                block[i] ^= dbMask[i];
            }

            block[0] &= 0x7f;

            //
            // find out how much padding we've got
            //
            int mStart = 0;

            while (mStart < block.Length)
            {
                if (block[mStart++] == 0x01)
                    break;
            }

            if (mStart >= block.Length)
            {
                ClearBlock(block);
            }

            fullMessage = (mStart > 1);

            recoveredMessage = new byte[dbMask.Length - mStart - saltLength];

            Array.Copy(block, mStart, recoveredMessage, 0, recoveredMessage.Length);
            recoveredMessage.CopyTo(mBuf, 0);

            preSig = signature;
            preBlock = block;
            preMStart = mStart;
            preTLength = tLength;
        }

        /// <summary> update the internal digest with the byte b</summary>
        public virtual void Update(
            byte input)
        {
            if (preSig == null && messageLength < mBuf.Length)
            {
                mBuf[messageLength++] = input;
            }
            else
            {
                digest.Update(input);
            }
        }

        /// <summary> update the internal digest with the byte array in</summary>
        public virtual void BlockUpdate(
            byte[]	input,
            int		inOff,
            int		length)
        {
            if (preSig == null)
            {
                while (length > 0 && messageLength < mBuf.Length)
                {
                    this.Update(input[inOff]);
                    inOff++;
                    length--;
                }
            }

            if (length > 0)
            {
                digest.BlockUpdate(input, inOff, length);
            }
        }

        /// <summary> reset the internal state</summary>
        public virtual void Reset()
        {
            digest.Reset();
            messageLength = 0;
            if (mBuf != null)
            {
                ClearBlock(mBuf);
            }
            if (recoveredMessage != null)
            {
                ClearBlock(recoveredMessage);
                recoveredMessage = null;
            }
            fullMessage = false;
            if (preSig != null)
            {
                preSig = null;
                ClearBlock(preBlock);
                preBlock = null;
            }
        }

        /// <summary> Generate a signature for the loaded message using the key we were
        /// initialised with.
        /// </summary>
        public virtual byte[] GenerateSignature()
        {
            int digSize = digest.GetDigestSize();
            byte[] m2Hash = new byte[digSize];
            digest.DoFinal(m2Hash, 0);

            byte[] C = new byte[8];
            LtoOSP(messageLength * 8, C);

            digest.BlockUpdate(C, 0, C.Length);
            digest.BlockUpdate(mBuf, 0, messageLength);
            digest.BlockUpdate(m2Hash, 0, m2Hash.Length);

            byte[] salt;
            if (standardSalt != null)
            {
                salt = standardSalt;
            }
            else
            {
                salt = new byte[saltLength];
                random.NextBytes(salt);
            }

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

            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);

            int tLength = 2;
            if (trailer == TrailerImplicit)
            {
                tLength = 1;
            }

            int off = block.Length - messageLength - salt.Length - hLen - tLength - 1;

            block[off] = (byte) (0x01);

            Array.Copy(mBuf, 0, block, off + 1, messageLength);
            Array.Copy(salt, 0, block, off + 1 + messageLength, salt.Length);

            byte[] dbMask = MaskGeneratorFunction1(hash, 0, hash.Length, block.Length - hLen - tLength);
            for (int i = 0; i != dbMask.Length; i++)
            {
                block[i] ^= dbMask[i];
            }

            Array.Copy(hash, 0, block, block.Length - hLen - tLength, hLen);

            if (trailer == TrailerImplicit)
            {
                block[block.Length - 1] = (byte)TrailerImplicit;
            }
            else
            {
                block[block.Length - 2] = (byte) ((uint)trailer >> 8);
                block[block.Length - 1] = (byte) trailer;
            }

            block[0] &= (byte) (0x7f);

            byte[] b = cipher.ProcessBlock(block, 0, block.Length);

            ClearBlock(mBuf);
            ClearBlock(block);
            messageLength = 0;

            return b;
        }

        /// <summary> return true if the signature represents a ISO9796-2 signature
        /// for the passed in message.
        /// </summary>
        public virtual bool VerifySignature(
            byte[] signature)
        {
            //
            // calculate H(m2)
            //
            byte[] m2Hash = new byte[hLen];
            digest.DoFinal(m2Hash, 0);

            byte[] block;
            int tLength;
            int mStart = 0;

            if (preSig == null)
            {
                try
                {
                    UpdateWithRecoveredMessage(signature);
                }
                catch (Exception)
                {
                    return false;
                }
            }
            else
            {
                if (!Arrays.AreEqual(preSig, signature))
                {
                    throw new InvalidOperationException("UpdateWithRecoveredMessage called on different signature");
                }
            }

            block = preBlock;
            mStart = preMStart;
            tLength = preTLength;

            preSig = null;
            preBlock = null;

            //
            // check the hashes
            //
            byte[] C = new byte[8];
            LtoOSP(recoveredMessage.Length * 8, C);

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

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

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

            // Update for the salt
            digest.BlockUpdate(block, mStart + recoveredMessage.Length, saltLength);

            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);

            int off = block.Length - tLength - hash.Length;

            bool isOkay = true;

            for (int i = 0; i != hash.Length; i++)
            {
                if (hash[i] != block[off + i])
                {
                    isOkay = false;
                }
            }

            ClearBlock(block);
            ClearBlock(hash);

            if (!isOkay)
            {
                fullMessage = false;
                ClearBlock(recoveredMessage);
                return false;
            }

            //
            // if they've input a message check what we've recovered against
            // what was input.
            //
            if (messageLength != 0)
            {
                if (!IsSameAs(mBuf, recoveredMessage))
                {
                    ClearBlock(mBuf);
                    return false;
                }
                messageLength = 0;
            }

            ClearBlock(mBuf);
            return true;
        }

        /// <summary>
        /// Return true if the full message was recoveredMessage.
        /// </summary>
        /// <returns>true on full message recovery, false otherwise, or if not sure.</returns>
        /// <seealso cref="ISignerWithRecovery.HasFullMessage"/>
        public virtual bool HasFullMessage()
        {
            return fullMessage;
        }

        /// <summary> int to octet string.</summary>
        /// <summary> int to octet string.</summary>
        private void ItoOSP(
            int		i,
            byte[]	sp)
        {
            sp[0] = (byte)((uint)i >> 24);
            sp[1] = (byte)((uint)i >> 16);
            sp[2] = (byte)((uint)i >> 8);
            sp[3] = (byte)((uint)i >> 0);
        }

        /// <summary> long to octet string.</summary>
        private void  LtoOSP(long l, byte[] sp)
        {
            sp[0] = (byte)((ulong)l >> 56);
            sp[1] = (byte)((ulong)l >> 48);
            sp[2] = (byte)((ulong)l >> 40);
            sp[3] = (byte)((ulong)l >> 32);
            sp[4] = (byte)((ulong)l >> 24);
            sp[5] = (byte)((ulong)l >> 16);
            sp[6] = (byte)((ulong)l >> 8);
            sp[7] = (byte)((ulong)l >> 0);
        }

        /// <summary> mask generator function, as described in Pkcs1v2.</summary>
        private byte[] MaskGeneratorFunction1(
            byte[]	Z,
            int		zOff,
            int		zLen,
            int		length)
        {
            byte[] mask = new byte[length];
            byte[] hashBuf = new byte[hLen];
            byte[] C = new byte[4];
            int counter = 0;

            digest.Reset();

            do
            {
                ItoOSP(counter, C);

                digest.BlockUpdate(Z, zOff, zLen);
                digest.BlockUpdate(C, 0, C.Length);
                digest.DoFinal(hashBuf, 0);

                Array.Copy(hashBuf, 0, mask, counter * hLen, hLen);
            }
            while (++counter < (length / hLen));

            if ((counter * hLen) < length)
            {
                ItoOSP(counter, C);

                digest.BlockUpdate(Z, zOff, zLen);
                digest.BlockUpdate(C, 0, C.Length);
                digest.DoFinal(hashBuf, 0);

                Array.Copy(hashBuf, 0, mask, counter * hLen, mask.Length - (counter * hLen));
            }

            return mask;
        }
    }
}