Line data Source code
1 : /* Copyright (C) 2025 Wildfire Games. 2 : * This file is part of 0 A.D. 3 : * 4 : * 0 A.D. is free software: you can redistribute it and/or modify 5 : * it under the terms of the GNU General Public License as published by 6 : * the Free Software Foundation, either version 2 of the License, or 7 : * (at your option) any later version. 8 : * 9 : * 0 A.D. is distributed in the hope that it will be useful, 10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 : * GNU General Public License for more details. 13 : * 14 : * You should have received a copy of the GNU General Public License 15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>. 16 : */ 17 : #include "precompiled.h" 18 : 19 : #include "lib/debug.h" 20 : #include "ps/CStr.h" 21 : #include "ps/Util.h" 22 : 23 : #include <cstddef> 24 : #include <sodium.h> 25 : #include <string> 26 : 27 15 : CStr8 HashCryptographically(const CStr8& string, const CStr8& salt) 28 : { 29 15 : if (string.empty()) 30 17 : return string; 31 : 32 13 : ENSURE(sodium_init() >= 0); 33 : 34 13 : constexpr int SALTSIZE = crypto_pwhash_SALTBYTES; 35 13 : static_assert(SALTSIZE >= crypto_generichash_BYTES_MIN); 36 13 : static_assert(SALTSIZE <= crypto_generichash_BYTES_MAX); 37 13 : static_assert(SALTSIZE >= crypto_generichash_KEYBYTES_MIN); 38 13 : static_assert(SALTSIZE <= crypto_generichash_KEYBYTES_MAX); 39 : 40 : // First generate a fixed-size salt from out variable-sized one (libsodium requires it). 41 13 : unsigned char salt_buffer[SALTSIZE] = { 42 : 235, 82, 29, 20, 135, 168, 184, 97, 7, 240, 48, 109, 8, 34, 158, 32, 43 : }; 44 13 : crypto_generichash_state state; 45 13 : crypto_generichash_init(&state, salt_buffer, SALTSIZE, SALTSIZE); 46 13 : crypto_generichash_update(&state, reinterpret_cast<const unsigned char*>(salt.c_str()), salt.size()); 47 13 : crypto_generichash_final(&state, salt_buffer, SALTSIZE); 48 : 49 13 : constexpr int HASHSIZE = 32; 50 13 : static_assert(HASHSIZE >= crypto_pwhash_BYTES_MIN); 51 13 : static_assert(HASHSIZE <= crypto_pwhash_BYTES_MAX); 52 : 53 : // Now that we have a fixed-length key, use that to hash the password. 54 13 : unsigned char output[HASHSIZE] = { 0 }; 55 : // For HashCryptographically, we use 'fast' parameters, corresponding to low values. 56 : // These parameters must not change, or hashes will change, hence why the #defined values are copied. 57 13 : constexpr size_t memLimit = 8192 * 4; // 4 * crypto_pwhash_argon2id_MEMLIMIT_MIN 58 13 : constexpr size_t opsLimit = 2; // crypto_pwhash_argon2id_OPSLIMIT_INTERACTIVE 59 13 : ENSURE(crypto_pwhash(output, HASHSIZE, string.c_str(), string.size(), salt_buffer, opsLimit, memLimit, crypto_pwhash_ALG_ARGON2ID13) == 0); 60 : 61 52 : return CStr(Hexify(output, HASHSIZE)).UpperCase(); 62 : }