summary refs log tree commit diff
path: root/crypto/src/crypto/encodings/Pkcs1Encoding.cs
blob: 06e59d4f35e6cb03227c8e5af0d0b4b5bf1c1d85 (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
using System;

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

namespace Org.BouncyCastle.Crypto.Encodings
{
    /**
    * this does your basic Pkcs 1 v1.5 padding - whether or not you should be using this
    * depends on your application - see Pkcs1 Version 2 for details.
    */
    public class Pkcs1Encoding
        : IAsymmetricBlockCipher
    {
        /**
         * some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to
         * work with one of these set the system property Org.BouncyCastle.Pkcs1.Strict to false.
         */
        public const string StrictLengthEnabledProperty = "Org.BouncyCastle.Pkcs1.Strict";

        private const int HeaderLength = 10;

        /**
         * The same effect can be achieved by setting the static property directly
         * <p>
         * The static property is checked during construction of the encoding object, it is set to
         * true by default.
         * </p>
         */
        public static bool StrictLengthEnabled
        {
            get { return strictLengthEnabled[0]; }
            set { strictLengthEnabled[0] = value; }
        }

        private static readonly bool[] strictLengthEnabled;

        static Pkcs1Encoding()
        {
            string strictProperty = Platform.GetEnvironmentVariable(StrictLengthEnabledProperty);

            strictLengthEnabled = new bool[]{ strictProperty == null || Platform.EqualsIgnoreCase("true", strictProperty) };
        }


        private SecureRandom random;
        private IAsymmetricBlockCipher engine;
        private bool forEncryption;
        private bool forPrivateKey;
        private bool useStrictLength;
        private int pLen = -1;
        private byte[] fallback = null;
        private byte[] blockBuffer = null;

        /**
         * Basic constructor.
         *
         * @param cipher
         */
        public Pkcs1Encoding(
            IAsymmetricBlockCipher cipher)
        {
            this.engine = cipher;
            this.useStrictLength = StrictLengthEnabled;
        }

        /**
         * Constructor for decryption with a fixed plaintext length.
         * 
         * @param cipher The cipher to use for cryptographic operation.
         * @param pLen Length of the expected plaintext.
         */
        public Pkcs1Encoding(IAsymmetricBlockCipher cipher, int pLen)
        {
            this.engine = cipher;
            this.useStrictLength = StrictLengthEnabled;
            this.pLen = pLen;
        }

        /**
         * Constructor for decryption with a fixed plaintext length and a fallback
         * value that is returned, if the padding is incorrect.
         * 
         * @param cipher
         *            The cipher to use for cryptographic operation.
         * @param fallback
         *            The fallback value, we don't to a arraycopy here.
         */
        public Pkcs1Encoding(IAsymmetricBlockCipher cipher, byte[] fallback)
        {
            this.engine = cipher;
            this.useStrictLength = StrictLengthEnabled;
            this.fallback = fallback;
            this.pLen = fallback.Length;
        }

        public string AlgorithmName => engine.AlgorithmName + "/PKCS1Padding";

        public IAsymmetricBlockCipher UnderlyingCipher => engine;

        public void Init(bool forEncryption, ICipherParameters parameters)
        {
            AsymmetricKeyParameter kParam;
            if (parameters is ParametersWithRandom withRandom)
            {
                this.random = withRandom.Random;
                kParam = (AsymmetricKeyParameter)withRandom.Parameters;
            }
            else
            {
                this.random = CryptoServicesRegistrar.GetSecureRandom();
                kParam = (AsymmetricKeyParameter)parameters;
            }

            engine.Init(forEncryption, parameters);

            this.forPrivateKey = kParam.IsPrivate;
            this.forEncryption = forEncryption;
            this.blockBuffer = new byte[engine.GetOutputBlockSize()];

            if (pLen > 0 && fallback == null && random == null)
                throw new ArgumentException("encoder requires random");
        }

        public int GetInputBlockSize()
        {
            int baseBlockSize = engine.GetInputBlockSize();

            return forEncryption
                ?	baseBlockSize - HeaderLength
                :	baseBlockSize;
        }

        public int GetOutputBlockSize()
        {
            int baseBlockSize = engine.GetOutputBlockSize();

            return forEncryption
                ?	baseBlockSize
                :	baseBlockSize - HeaderLength;
        }

        public byte[] ProcessBlock(
            byte[]	input,
            int		inOff,
            int		length)
        {
            return forEncryption
                ?	EncodeBlock(input, inOff, length)
                :	DecodeBlock(input, inOff, length);
        }

        private byte[] EncodeBlock(
            byte[]	input,
            int		inOff,
            int		inLen)
        {
            if (inLen > GetInputBlockSize())
                throw new ArgumentException("input data too large", "inLen");

            byte[] block = new byte[engine.GetInputBlockSize()];

            if (forPrivateKey)
            {
                block[0] = 0x01;                        // type code 1

                for (int i = 1; i != block.Length - inLen - 1; i++)
                {
                    block[i] = (byte)0xFF;
                }
            }
            else
            {
                random.NextBytes(block);                // random fill

                block[0] = 0x02;                        // type code 2

                //
                // a zero byte marks the end of the padding, so all
                // the pad bytes must be non-zero.
                //
                for (int i = 1; i != block.Length - inLen - 1; i++)
                {
                    while (block[i] == 0)
                    {
                        block[i] = (byte)random.NextInt();
                    }
                }
            }

            block[block.Length - inLen - 1] = 0x00;       // mark the end of the padding
            Array.Copy(input, inOff, block, block.Length - inLen, inLen);

            return engine.ProcessBlock(block, 0, block.Length);
        }

        /**
         * Checks if the argument is a correctly PKCS#1.5 encoded Plaintext
         * for encryption.
         * 
         * @param encoded The Plaintext.
         * @param pLen Expected length of the plaintext.
         * @return Either 0, if the encoding is correct, or -1, if it is incorrect.
         */
        private static int CheckPkcs1Encoding(byte[] encoded, int pLen)
        {
            int correct = 0;
            /*
             * Check if the first two bytes are 0 2
             */
            correct |= (encoded[0] ^ 2);

            /*
             * Now the padding check, check for no 0 byte in the padding
             */
            int plen = encoded.Length - (
                      pLen /* Length of the PMS */
                    +  1 /* Final 0-byte before PMS */
            );

            for (int i = 1; i < plen; i++)
            {
                int tmp = encoded[i];
                tmp |= tmp >> 1;
                tmp |= tmp >> 2;
                tmp |= tmp >> 4;
                correct |= (tmp & 1) - 1;
            }

            /*
             * Make sure the padding ends with a 0 byte.
             */
            correct |= encoded[encoded.Length - (pLen + 1)];

            /*
             * Return 0 or 1, depending on the result.
             */
            correct |= correct >> 1;
            correct |= correct >> 2;
            correct |= correct >> 4;
            return ~((correct & 1) - 1);
        }

        /**
         * Decode PKCS#1.5 encoding, and return a random value if the padding is not correct.
         * 
         * @param in The encrypted block.
         * @param inOff Offset in the encrypted block.
         * @param inLen Length of the encrypted block.
         * @param pLen Length of the desired output.
         * @return The plaintext without padding, or a random value if the padding was incorrect.
         * @throws InvalidCipherTextException
         */
        private byte[] DecodeBlockOrRandom(byte[] input, int inOff, int inLen)
        {
            if (!forPrivateKey)
                throw new InvalidCipherTextException("sorry, this method is only for decryption, not for signing");

            byte[] block = engine.ProcessBlock(input, inOff, inLen);
            byte[] random;
            if (this.fallback == null)
            {
                random = new byte[this.pLen];
                this.random.NextBytes(random);
            }
            else
            {
                random = fallback;
            }

            byte[] data = (useStrictLength & (block.Length != engine.GetOutputBlockSize())) ? blockBuffer : block;

		    /*
		     * Check the padding.
		     */
            int correct = CheckPkcs1Encoding(data, this.pLen);

		    /*
		     * Now, to a constant time constant memory copy of the decrypted value
		     * or the random value, depending on the validity of the padding.
		     */
            byte[] result = new byte[this.pLen];
            for (int i = 0; i < this.pLen; i++)
            {
                result[i] = (byte)((data[i + (data.Length - pLen)] & (~correct)) | (random[i] & correct));
            }

            Arrays.Fill(data, 0);

            return result;
        }

        /**
        * @exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format.
        */
        private byte[] DecodeBlock(
            byte[]	input,
            int		inOff,
            int		inLen)
        {
            /*
             * If the length of the expected plaintext is known, we use a constant-time decryption.
             * If the decryption fails, we return a random value.
             */
            if (this.pLen != -1)
            {
                return this.DecodeBlockOrRandom(input, inOff, inLen);
            }

            byte[] block = engine.ProcessBlock(input, inOff, inLen);
            bool incorrectLength = (useStrictLength & (block.Length != engine.GetOutputBlockSize()));

            byte[] data;
            if (block.Length < GetOutputBlockSize())
            {
                data = blockBuffer;
            }
            else
            {
                data = block;
            }

            byte expectedType = (byte)(forPrivateKey ? 2 : 1);
            byte type = data[0];

            bool badType = (type != expectedType);

            //
            // find and extract the message block.
            //
            int start = FindStart(type, data);

            start++;           // data should start at the next byte

            if (badType | (start < HeaderLength))
            {
                Arrays.Fill(data, 0);
                throw new InvalidCipherTextException("block incorrect");
            }

            // if we get this far, it's likely to be a genuine encoding error
            if (incorrectLength)
            {
                Arrays.Fill(data, 0);
                throw new InvalidCipherTextException("block incorrect size");
            }

            byte[] result = new byte[data.Length - start];

            Array.Copy(data, start, result, 0, result.Length);

            return result;
        }

        private int FindStart(byte type, byte[] block)
        {
            int start = -1;
            bool padErr = false;

            for (int i = 1; i != block.Length; i++)
            {
                byte pad = block[i];

                if (pad == 0 & start < 0)
                {
                    start = i;
                }
                padErr |= ((type == 1) & (start < 0) & (pad != (byte)0xff));
            }

            return padErr ? -1 : start;
        }
    }
}