1 // This file is dual licensed under the terms of the Apache License, Version
2 // 2.0, and the BSD License. See the LICENSE file in the root of this
3 // repository for complete details.
4 
5 /* Returns the value of the input with the most-significant-bit copied to all
6    of the bits. */
Cryptography_DUPLICATE_MSB_TO_ALL(uint16_t a)7 static uint16_t Cryptography_DUPLICATE_MSB_TO_ALL(uint16_t a) {
8     return (1 - (a >> (sizeof(uint16_t) * 8 - 1))) - 1;
9 }
10 
11 /* This returns 0xFFFF if a < b else 0x0000, but does so in a constant time
12    fashion */
Cryptography_constant_time_lt(uint16_t a,uint16_t b)13 static uint16_t Cryptography_constant_time_lt(uint16_t a, uint16_t b) {
14     a -= b;
15     return Cryptography_DUPLICATE_MSB_TO_ALL(a);
16 }
17 
Cryptography_check_pkcs7_padding(const uint8_t * data,uint16_t block_len)18 uint8_t Cryptography_check_pkcs7_padding(const uint8_t *data,
19                                          uint16_t block_len) {
20     uint16_t i;
21     uint16_t pad_size = data[block_len - 1];
22     uint16_t mismatch = 0;
23     for (i = 0; i < block_len; i++) {
24         unsigned int mask = Cryptography_constant_time_lt(i, pad_size);
25         uint16_t b = data[block_len - 1 - i];
26         mismatch |= (mask & (pad_size ^ b));
27     }
28 
29     /* Check to make sure the pad_size was within the valid range. */
30     mismatch |= ~Cryptography_constant_time_lt(0, pad_size);
31     mismatch |= Cryptography_constant_time_lt(block_len, pad_size);
32 
33     /* Make sure any bits set are copied to the lowest bit */
34     mismatch |= mismatch >> 8;
35     mismatch |= mismatch >> 4;
36     mismatch |= mismatch >> 2;
37     mismatch |= mismatch >> 1;
38     /* Now check the low bit to see if it's set */
39     return (mismatch & 1) == 0;
40 }
41 
Cryptography_check_ansix923_padding(const uint8_t * data,uint16_t block_len)42 uint8_t Cryptography_check_ansix923_padding(const uint8_t *data,
43                                             uint16_t block_len) {
44     uint16_t i;
45     uint16_t pad_size = data[block_len - 1];
46     uint16_t mismatch = 0;
47     /* Skip the first one with the pad size */
48     for (i = 1; i < block_len; i++) {
49         unsigned int mask = Cryptography_constant_time_lt(i, pad_size);
50         uint16_t b = data[block_len - 1 - i];
51         mismatch |= (mask & b);
52     }
53 
54     /* Check to make sure the pad_size was within the valid range. */
55     mismatch |= ~Cryptography_constant_time_lt(0, pad_size);
56     mismatch |= Cryptography_constant_time_lt(block_len, pad_size);
57 
58     /* Make sure any bits set are copied to the lowest bit */
59     mismatch |= mismatch >> 8;
60     mismatch |= mismatch >> 4;
61     mismatch |= mismatch >> 2;
62     mismatch |= mismatch >> 1;
63     /* Now check the low bit to see if it's set */
64     return (mismatch & 1) == 0;
65 }
66