crypt.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Base64.h>
  7. #include <AK/Types.h>
  8. #include <LibCrypto/Hash/SHA2.h>
  9. #include <crypt.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. extern "C" {
  13. static struct crypt_data crypt_data;
  14. char* crypt(char const* key, char const* salt)
  15. {
  16. crypt_data.initialized = true;
  17. return crypt_r(key, salt, &crypt_data);
  18. }
  19. static constexpr size_t crypt_salt_max = 16;
  20. char* crypt_r(char const* key, char const* salt, struct crypt_data* data)
  21. {
  22. if (!data->initialized) {
  23. errno = EINVAL;
  24. return nullptr;
  25. }
  26. // We only support SHA-256 at the moment
  27. if (salt[0] != '$' || salt[1] != '5') {
  28. errno = EINVAL;
  29. return nullptr;
  30. }
  31. char const* salt_value = salt + 3;
  32. size_t salt_len = min(strcspn(salt_value, "$"), crypt_salt_max);
  33. size_t header_len = salt_len + 3;
  34. bool fits = ByteString(salt, header_len).copy_characters_to_buffer(data->result, sizeof(data->result));
  35. if (!fits) {
  36. errno = EINVAL;
  37. return nullptr;
  38. }
  39. data->result[header_len] = '$';
  40. Crypto::Hash::SHA256 sha;
  41. sha.update(StringView { key, strlen(key) });
  42. sha.update(reinterpret_cast<u8 const*>(salt_value), salt_len);
  43. auto digest = sha.digest();
  44. auto string_or_error = encode_base64({ digest.immutable_data(), digest.data_length() });
  45. if (string_or_error.is_error()) {
  46. errno = ENOMEM;
  47. return nullptr;
  48. }
  49. auto string = string_or_error.value().bytes_as_string_view();
  50. fits = string.copy_characters_to_buffer(data->result + header_len + 1, sizeof(data->result) - header_len - 1);
  51. if (!fits) {
  52. errno = EINVAL;
  53. return nullptr;
  54. }
  55. return data->result;
  56. }
  57. }