2020-07-24 21:08:48 -06:00
|
|
|
/*
|
2021-08-31 19:32:46 -07:00
|
|
|
* Copyright (c) 2020, Peter Elliott <pelliott@serenityos.org>
|
2020-07-24 21:08:48 -06:00
|
|
|
*
|
2021-04-22 01:24:48 -07:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-07-24 21:08:48 -06:00
|
|
|
*/
|
2021-05-15 00:27:09 +01:00
|
|
|
|
2020-07-24 21:08:48 -06:00
|
|
|
#include <AK/Base64.h>
|
|
|
|
|
#include <AK/Types.h>
|
|
|
|
|
#include <LibCrypto/Hash/SHA2.h>
|
2021-05-01 11:38:19 +02:00
|
|
|
#include <crypt.h>
|
|
|
|
|
#include <errno.h>
|
2020-07-24 21:08:48 -06:00
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
|
|
extern "C" {
|
|
|
|
|
|
|
|
|
|
static struct crypt_data crypt_data;
|
|
|
|
|
|
2022-04-01 20:58:27 +03:00
|
|
|
char* crypt(char const* key, char const* salt)
|
2020-07-24 21:08:48 -06:00
|
|
|
{
|
|
|
|
|
crypt_data.initialized = true;
|
|
|
|
|
return crypt_r(key, salt, &crypt_data);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static constexpr size_t crypt_salt_max = 16;
|
|
|
|
|
static constexpr size_t sha_string_length = 44;
|
|
|
|
|
|
2022-04-01 20:58:27 +03:00
|
|
|
char* crypt_r(char const* key, char const* salt, struct crypt_data* data)
|
2020-07-24 21:08:48 -06:00
|
|
|
{
|
|
|
|
|
if (!data->initialized) {
|
|
|
|
|
errno = EINVAL;
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (salt[0] == '$') {
|
|
|
|
|
if (salt[1] == '5') {
|
2022-04-01 20:58:27 +03:00
|
|
|
char const* salt_value = salt + 3;
|
2020-07-24 21:08:48 -06:00
|
|
|
size_t salt_len = min(strcspn(salt_value, "$"), crypt_salt_max);
|
|
|
|
|
size_t header_len = salt_len + 3;
|
|
|
|
|
|
2020-08-25 17:32:01 +03:00
|
|
|
bool fits = String(salt, header_len).copy_characters_to_buffer(data->result, sizeof(data->result));
|
|
|
|
|
if (!fits) {
|
|
|
|
|
errno = EINVAL;
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
2020-07-24 21:08:48 -06:00
|
|
|
data->result[header_len] = '$';
|
|
|
|
|
|
|
|
|
|
Crypto::Hash::SHA256 sha;
|
2022-07-11 19:53:29 +00:00
|
|
|
sha.update(StringView { key, strlen(key) });
|
2022-04-01 20:58:27 +03:00
|
|
|
sha.update((u8 const*)salt_value, salt_len);
|
2020-07-24 21:08:48 -06:00
|
|
|
|
|
|
|
|
auto digest = sha.digest();
|
|
|
|
|
auto string = encode_base64(ReadonlyBytes(digest.immutable_data(), digest.data_length()));
|
|
|
|
|
|
2020-08-25 17:32:01 +03:00
|
|
|
fits = string.copy_characters_to_buffer(data->result + header_len + 1, sizeof(data->result) - header_len - 1);
|
|
|
|
|
if (!fits) {
|
|
|
|
|
errno = EINVAL;
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
2020-07-24 21:08:48 -06:00
|
|
|
|
|
|
|
|
return data->result;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DES crypt is not available.
|
|
|
|
|
errno = EINVAL;
|
|
|
|
|
return nullptr;
|
|
|
|
|
}
|
|
|
|
|
}
|