crypt.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /* Copyright (C) 2020 Steffen Jaeckel <jaeckel-floss@eyet-services.de> */
  3. #include <common.h>
  4. #include <crypt.h>
  5. #include "crypt-port.h"
  6. typedef int (*crypt_fn)(const char *, size_t, const char *, size_t, uint8_t *,
  7. size_t, void *, size_t);
  8. const unsigned char ascii64[65] =
  9. "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  10. static void equals_constant_time(const void *a_, const void *b_, size_t len,
  11. int *equal)
  12. {
  13. u8 ret = 0;
  14. const u8 *a = a_, *b = b_;
  15. int i;
  16. for (i = 0; i < len; i++)
  17. ret |= a[i] ^ b[i];
  18. ret |= ret >> 4;
  19. ret |= ret >> 2;
  20. ret |= ret >> 1;
  21. ret &= 1;
  22. *equal = ret ^ 1;
  23. }
  24. int crypt_compare(const char *should, const char *passphrase, int *equal)
  25. {
  26. u8 output[CRYPT_OUTPUT_SIZE], scratch[ALG_SPECIFIC_SIZE];
  27. size_t n;
  28. int err;
  29. struct {
  30. const char *prefix;
  31. crypt_fn crypt;
  32. } crypt_algos[] = {
  33. #if defined(CONFIG_CRYPT_PW_SHA256)
  34. { "$5$", crypt_sha256crypt_rn_wrapped },
  35. #endif
  36. #if defined(CONFIG_CRYPT_PW_SHA512)
  37. { "$6$", crypt_sha512crypt_rn_wrapped },
  38. #endif
  39. { NULL, NULL }
  40. };
  41. *equal = 0;
  42. for (n = 0; n < ARRAY_SIZE(crypt_algos); ++n) {
  43. if (!crypt_algos[n].prefix)
  44. continue;
  45. if (strncmp(should, crypt_algos[n].prefix, 3) == 0)
  46. break;
  47. }
  48. if (n >= ARRAY_SIZE(crypt_algos))
  49. return -EINVAL;
  50. err = crypt_algos[n].crypt(passphrase, strlen(passphrase), should, 0,
  51. output, sizeof(output), scratch,
  52. sizeof(scratch));
  53. /* early return on error, nothing really happened inside the crypt() function */
  54. if (err)
  55. return err;
  56. equals_constant_time(should, output, strlen((const char *)output),
  57. equal);
  58. memset(scratch, 0, sizeof(scratch));
  59. memset(output, 0, sizeof(output));
  60. return 0;
  61. }