crypt.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 void (*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. void 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. struct {
  29. const char *prefix;
  30. crypt_fn crypt;
  31. } crypt_algos[] = {
  32. #if defined(CONFIG_CRYPT_PW_SHA256)
  33. { "$5$", crypt_sha256crypt_rn },
  34. #endif
  35. #if defined(CONFIG_CRYPT_PW_SHA512)
  36. { "$6$", crypt_sha512crypt_rn },
  37. #endif
  38. { NULL, NULL }
  39. };
  40. *equal = 0;
  41. for (n = 0; n < ARRAY_SIZE(crypt_algos); ++n) {
  42. if (!crypt_algos[n].prefix)
  43. continue;
  44. if (strncmp(should, crypt_algos[n].prefix, 3) == 0)
  45. break;
  46. }
  47. if (n >= ARRAY_SIZE(crypt_algos))
  48. return;
  49. crypt_algos[n].crypt(passphrase, strlen(passphrase), should, 0, output,
  50. sizeof(output), scratch, sizeof(scratch));
  51. /* early return on error, nothing really happened inside the crypt() function */
  52. if (errno == ERANGE || errno == EINVAL)
  53. return;
  54. equals_constant_time(should, output, strlen((const char *)output),
  55. equal);
  56. memset(scratch, 0, sizeof(scratch));
  57. memset(output, 0, sizeof(output));
  58. }