padding.c 2.4 KB

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