Files
dolphin/Source/Core/Common/Crypto/SHA1.h
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

88 lines
2.1 KiB
C++
Raw Normal View History

2022-07-23 22:45:10 -07:00
// Copyright 2017 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <array>
#include <limits>
#include <memory>
#include <span>
2022-07-23 22:45:10 -07:00
#include <string_view>
#include <type_traits>
#include <vector>
#include "Common/Assert.h"
#include "Common/CommonTypes.h"
namespace Common::SHA1
{
using Digest = std::array<u8, 160 / 8>;
static constexpr size_t DIGEST_LEN = sizeof(Digest);
class Context
{
public:
virtual ~Context() = default;
virtual void Update(const u8* msg, size_t len) = 0;
void Update(std::span<const u8> msg) { return Update(msg.data(), msg.size()); }
void Update(std::string_view msg)
{
return Update(reinterpret_cast<const u8*>(msg.data()), msg.size());
}
2022-07-23 22:45:10 -07:00
virtual Digest Finish() = 0;
virtual bool HwAccelerated() const = 0;
2022-07-23 22:45:10 -07:00
};
std::unique_ptr<Context> CreateContext();
Digest CalculateDigest(const u8* msg, size_t len);
template <typename T>
inline Digest CalculateDigest(const std::vector<T>& msg)
{
static_assert(std::is_trivially_copyable_v<T>);
ASSERT(std::numeric_limits<size_t>::max() / sizeof(T) >= msg.size());
return CalculateDigest(reinterpret_cast<const u8*>(msg.data()), sizeof(T) * msg.size());
}
inline Digest CalculateDigest(const std::string_view& msg)
{
return CalculateDigest(reinterpret_cast<const u8*>(msg.data()), msg.size());
}
template <typename T, size_t Size>
inline Digest CalculateDigest(const std::array<T, Size>& msg)
{
static_assert(std::is_trivially_copyable_v<T>);
return CalculateDigest(reinterpret_cast<const u8*>(msg.data()), sizeof(msg));
}
std::string DigestToString(const Digest& digest);
constexpr Digest StringToDigest(std::string_view str)
{
Digest digest{};
ASSERT(str.size() == digest.size() * 2);
for (size_t i = 0; i < str.size(); ++i)
{
const char c = str[i];
u8 quartet;
if (c >= '0' && c <= '9')
quartet = c - '0';
else if (c >= 'A' && c <= 'F')
quartet = c - 'A' + 10;
else if (c >= 'a' && c <= 'f')
quartet = c - 'a' + 10;
else
ASSERT(false);
if (i % 2 == 0)
digest[i / 2] = quartet << 4;
else
digest[i / 2] |= quartet;
}
return digest;
}
2022-07-23 22:45:10 -07:00
} // namespace Common::SHA1