1

Есть один код в котором выполняется действие преобразование в хэш пунка VERIFIER но он немного не правильный, в каком месте он не правильный точно сказать не могу, так как на одном ядре он работает правильно, а на том ядре где он мне нужен он генерирует не тот хэш И при вводе Логина : Admin
и Пароля: 0314530886
В базе хранится Verifier хэш: FB377317378486B25D05FCABBBBFCF2C4AD85DE672BB982CFD87099955499E5C
и Salt Hash: 75B09DA1005F907383FDA1CDA1292F461DA913C1F3256B5DECD1F4624C667A86

Verifier выводится совсем другой, помогите пожалуйста разобраться.

    using System.Text;
    using System.Numerics;
    using System.Security.Cryptography;
    using System.Globalization;
      
    public class SRP6
    {

        private BigInteger n = BigInteger.Parse("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", NumberStyles.AllowHexSpecifier);

        private BigInteger g = new byte[] { 7 }.ToBigInteger();

        private readonly byte[] v = new byte[32];

        private readonly byte[] s = new byte[32];

        /// <summary>
        /// Только для чтения: Соль.
        /// </summary>
        /// <returns></returns>
        public string Salt
        {
            get
            {
                return s.Reverse().ToHexString();
            }
        }

        /// <summary>
        /// Только для чтения: Верификатор.
        /// </summary>
        /// <returns></returns>
        public string Verifier
        {
            get
            {
                return v.Reverse().ToHexString();
            }
        }

        /// <summary>
        /// Конструктор инициализации.
        /// </summary>
        /// <param name="username">Имя пользователя.</param>
        /// <param name="password">Пароль.</param>
        /// <param name="salt">Предустановленная соль.</param>
        public SRP6(string username, string password, string salt = "")
        {

            if (string.IsNullOrEmpty(salt))
            {
                // Генерим Salt
                using (var rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(s);
                }
            }
            else
            {
                s = salt.ToByteArray().Reverse();
            }

            // Генерим H2 = H(s | H(P))
            var p = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(username.Trim().ToUpper() + ":" + password.Trim().ToUpper()));
            var h2 = SHA1.Create().ComputeHash(s.Combine(p)).ToBigInteger();

            // Генерим v = g ^ H2 % N
            v = BigInteger.ModPow(g, h2, n).ToByteArray();

        }

    }

    internal static class Extensions
    {

        public static byte[] Combine(this byte[] data1, byte[] data2)
        {
            return new byte[0].Concat(data1).Concat(data2).ToArray();
        }

        public static string ToHexString(this byte[] data)
        {
            StringBuilder hex = new StringBuilder(data.Length * 2);
            foreach (byte b in data)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString().ToUpper();
        }

        public static byte[] ToByteArray(this string s)
        {
            var data = new byte[(s.Length / 2)];
            for (int i = 0; i < s.Length; i += 2)
            {
                data[i / 2] = Convert.ToByte(s.Substring(i, 2), 16);
            }
            return data;
        }

        public static BigInteger ToBigInteger(this byte[] value, bool isBigEndian = false)
        {
            if (isBigEndian)
            {
                Array.Reverse(value);
            }
            return new BigInteger(value.Combine(new byte[] { 0 }));
        }

        public static byte[] Reverse(this byte[] data)
        {
            Array.Reverse(data);
            return data;
        }

    }

И правильный код написанный на C++ (Не могу определить что не правильно в коде C# так как в C++ не разбераюсь) ВОТ сам код:

/*static*/ std::array<uint8, 1> const SRP6::g = { 7 };
/*static*/ std::array<uint8, 32> const SRP6::N = HexStrToByteArray<32>("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", true);
/*static*/ BigNumber const SRP6::_g(SRP6::g);
/*static*/ BigNumber const SRP6::_N(N);
      
/*static*/ std::pair<SRP6::Salt, SRP6::Verifier> SRP6::MakeRegistrationData(std::string const& username, std::string const& password)
{
     std::pair<SRP6::Salt, SRP6::Verifier> res;
     Crypto::GetRandomBytes(res.first); // random salt
     res.second = CalculateVerifier(username, password, res.first);
     return res;
}
      
/*static*/ SRP6::Verifier SRP6::CalculateVerifier(std::string const& username, std::string const& password, SRP6::Salt const& salt)
{
     v = g ^ H(s || H(u || ':' || p)) mod N
     return _g.ModExp(
     SHA1::GetDigestOf(
     salt,
     SHA1::GetDigestOf(username, ":", password)
             )
         ,_N).ToByteArray<32>();
}
      
/*static*/ SessionKey SRP6::SHA1Interleave(SRP6::EphemeralKey const& S)
{
     split S into two buffers
     std::array<uint8, EPHEMERAL_KEY_LENGTH/2> buf0, buf1;
     for (size_t i = 0; i < EPHEMERAL_KEY_LENGTH/2; ++i)
     {
         buf0[i] = S[2 * i + 0];
         buf1[i] = S[2 * i + 1];
     }
      
     find position of first nonzero byte
     size_t p = 0;
     while (p < EPHEMERAL_KEY_LENGTH && !S[p]) ++p;
     if (p & 1) ++p; // skip one extra byte if p is odd
     p /= 2; // offset into buffers
      
     hash each of the halves, starting at the first nonzero byte
     SHA1::Digest const hash0 = SHA1::GetDigestOf(buf0.data() + p, EPHEMERAL_KEY_LENGTH/2 - p);
     SHA1::Digest const hash1 = SHA1::GetDigestOf(buf1.data() + p, EPHEMERAL_KEY_LENGTH/2 - p);
      
     stick the two hashes back together
     SessionKey K;
     for (size_t i = 0; i < SHA1::DIGEST_LENGTH; ++i)
     {
         K[2 * i + 0] = hash0[i];
         K[2 * i + 1] = hash1[i];
     }
     return K;
}
      
SRP6::SRP6(std::string const& username, Salt const& salt, Verifier const& verifier)
_I(SHA1::GetDigestOf(username)), _b(Crypto::GetRandomBytes<32>()), _v(verifier), s(salt), B(_B(_b, _v)) {}
      
std::optional<SessionKey> SRP6::VerifyChallengeResponse(EphemeralKey const& A, SHA1::Digest const& clientM)
{
     ASSERT(!_used, "A single SRP6 object must only ever be used to verify ONCE!");
     _used = true;
      
     BigNumber const _A(A);
     if ((_A % _N).IsZero())
     return std::nullopt;
      
     BigNumber const u(SHA1::GetDigestOf(A, B));
     EphemeralKey const S = (_A * (_v.ModExp(u, _N))).ModExp(_b, N).ToByteArray<32>();
      
     SessionKey K = SHA1Interleave(S);
      
     NgHash = H(N) xor H(g)
     SHA1::Digest const NHash = SHA1::GetDigestOf(N);
     SHA1::Digest const gHash = SHA1::GetDigestOf(g);
     SHA1::Digest NgHash;
     std::transform(NHash.begin(), NHash.end(), gHash.begin(), NgHash.begin(), std::bit_xor<>());
      
     SHA1::Digest const ourM = SHA1::GetDigestOf(NgHash, _I, s, A, B, K);
     if (ourM == clientM)
         return K;
     else
         return std::nullopt;
}

Так же есть код на PHP который так же правильно генерирует ХЭШ VERIFIER:

function CalculateSRP6Verifier($username, $password, $salt)
{
    // algorithm constants
       $g = gmp_init(7);
       $N = gmp_init('894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7', 16);
      
    // calculate first hash
       $h1 = sha1(strtoupper($username . ':' . $password), TRUE);
      
    // calculate second hash
       $h2 = sha1($salt . $h1, TRUE);
      
    // convert to integer (little-endian)
       $h2 = gmp_import($h2, 1, GMP_LSW_FIRST);
      
    // g^h2 mod N
       $verifier = gmp_powm($g, $h2, $N);
      
    // convert back to a byte array (little-endian)
       $verifier = gmp_export($verifier, 1, GMP_LSW_FIRST);
      
    // pad to 32 bytes, remember that zeros go on the end in little-endian!
       $verifier = str_pad($verifier, 32, chr(0), STR_PAD_RIGHT);
      
    // done!
     return $verifier;
}
      
function VerifySRP6Login($username, $password, $salt, $verifier)
{
    // re-calculate the verifier using the provided username + password and the stored salt
       $checkVerifier = CalculateSRP6Verifier($username, $password, $salt);
      
    // compare it against the stored verifier
     return ($verifier === $checkVerifier);
}
  1. Необходимо вычислить значение Хэша которое должно ровняться после вычисления кодом = FB377317378486B25D05FCABBBBFCF2C4AD85DE672BB982CFD87099955499E5C
  2. Есть информация по реализации данной функции от Разработчиков ядра по игре World of Warcraft 3,3,5 Сервер TRINITYCORE:
The account table contains salt and verifier columns containing the respective SRP6 values.

salt is a cryptographically random 32-byte value
verifier is derived from salt, as well as the user's username (all uppercase) and their password (all uppercase)
If you are registering a user, or changing a user's password, generate a random salt, then calculate the appropriate verifier, and store both in the database.
If you are logging a user in, re-calculate the verifier using the stored salt and their login details, and compare it against the stored verifier. If the values match, the login details are correct.

To obtain the verifier:

Calculate h1 = SHA1("USERNAME:PASSWORD"), substituting the user's username and password converted to uppercase
This is the old sha_pass_hash value!
Calculate h2 = SHA1(salt || h1), where || is concatenation (the . operator in PHP)
Note that both salt and h1 are binary, not hexadecimal strings!
Treat h2 as an integer in little-endian order (the first byte is the least significant)
Calculate (g ^ h2) % N
^ is modular exponentiation, % is the modulo operator
g and N are parameters, which are fixed in the WoW implementation:
g = 7
N = 0x894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7
Convert the result back to a byte array in little-endian order
This is your verifier - you're done!

Описано выше приведен код

2
  • 1
    Комментарии не предназначены для расширенной дискуссии; разговор перемещён в чат.
    – Grundy
    10 ноя 2022 в 18:39
  • Почему эта штука называется SRP6, если в настоящем SRP6 verifier не зависит от имени пользователя? 11 ноя 2022 в 5:23

1 ответ 1

1

Есть попадание

Это код .NET 6, кастомные расширения не нужны, всё уже встроено в .NET

public class SRP6
{
    private readonly BigInteger n = BigInteger.Parse("00894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7", NumberStyles.HexNumber);
    //                                                ^^ вот здесь проблема была, у вас n было отрицательное
    private readonly BigInteger g = 7;

    private readonly byte[] _verifier;
    private readonly byte[] _salt;

    public string Salt => Convert.ToHexString(_salt);

    public string Verifier => Convert.ToHexString(_verifier);

    public SRP6(string username, string password, string salt)
    {
        _salt = Convert.FromHexString(salt);
        var h1 = SHA1.HashData(Encoding.UTF8.GetBytes($"{username}:{password}".ToUpper()));
        var h2 = SHA1.HashData(_salt.Concat(h1).ToArray());
        _verifier = BigInteger.ModPow(g, new BigInteger(h2, true), n).ToByteArray();
    }
}

Проверяю

static void Main(string[] args)
{
    var srp6 = new SRP6("Admin", "0314530886", "75B09DA1005F907383FDA1CDA1292F461DA913C1F3256B5DECD1F4624C667A86");
    Console.WriteLine(srp6.Verifier);
    Console.WriteLine("FB377317378486B25D05FCABBBBFCF2C4AD85DE672BB982CFD87099955499E5C");
}

Вывод в консоль

FB377317378486B25D05FCABBBBFCF2C4AD85DE672BB982CFD87099955499E5C
FB377317378486B25D05FCABBBBFCF2C4AD85DE672BB982CFD87099955499E5C
1
  • 1
    Я очень вам благодарен , вы просто не представляете как , как тут поставить Макс оценку? 10 ноя 2022 в 18:48

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.