#include "components/crx_file/id_util.h"
#include <stdint.h>
#include <string_view>
#include "base/files/file_path.h"
#include "base/hash/sha1.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "crypto/hash.h"
#include "third_party/abseil-cpp/absl/strings/ascii.h"
namespace {
static void ConvertHexadecimalToIDAlphabet(std::string* id) {
for (auto& ch : *id) {
int val;
if (base::HexStringToInt(std::string_view(&ch, 1), &val)) {
ch = 'a' + val;
} else {
ch = 'a';
}
}
}
}
namespace crx_file::id_util {
const size_t kIdSize = 16;
std::string GenerateId(std::string_view input) {
return GenerateId(base::as_byte_span(input));
}
std::string GenerateId(base::span<const uint8_t> input) {
return GenerateIdFromHash(crypto::hash::Sha256(input));
}
std::string GenerateIdFromHash(base::span<const uint8_t> hash) {
std::string result = base::HexEncode(hash.first(kIdSize));
ConvertHexadecimalToIDAlphabet(&result);
return result;
}
std::string GenerateIdFromHex(const std::string& input) {
std::string output = input;
ConvertHexadecimalToIDAlphabet(&output);
return output;
}
std::string GenerateIdForPath(const base::FilePath& path) {
base::FilePath new_path = MaybeNormalizePath(path);
return GenerateId(base::as_byte_span(new_path.value()));
}
std::string HashedIdInHex(const std::string& id) {
return base::HexEncode(base::SHA1Hash(base::as_byte_span(id)));
}
base::FilePath MaybeNormalizePath(const base::FilePath& path) {
#if BUILDFLAG(IS_WIN)
base::FilePath::StringType path_str = path.value();
if (path_str.size() >= 2 && path_str[0] >= L'a' && path_str[0] <= L'z' &&
path_str[1] == L':') {
path_str[0] = absl::ascii_toupper(static_cast<unsigned char>(path_str[0]));
}
return base::FilePath(path_str);
#else
return path;
#endif
}
bool IdIsValid(std::string_view id) {
if (id.size() != (crx_file::id_util::kIdSize * 2)) {
return false;
}
for (char ch : id) {
ch = base::ToLowerASCII(ch);
if (ch < 'a' || ch > 'p') {
return false;
}
}
return true;
}
}