This source file includes following definitions.
- ConvertHexadecimalToIDAlphabet
- GenerateId
- GenerateIdForPath
- MaybeNormalizePath
#include "extensions/common/id_util.h"
#include "base/files/file_path.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "crypto/sha2.h"
namespace {
static void ConvertHexadecimalToIDAlphabet(std::string* id) {
for (size_t i = 0; i < id->size(); ++i) {
int val;
if (base::HexStringToInt(base::StringPiece(id->begin() + i,
id->begin() + i + 1),
&val)) {
(*id)[i] = val + 'a';
} else {
(*id)[i] = 'a';
}
}
}
}
namespace extensions {
namespace id_util {
const size_t kIdSize = 16;
std::string GenerateId(const std::string& input) {
uint8 hash[kIdSize];
crypto::SHA256HashString(input, hash, sizeof(hash));
std::string output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
ConvertHexadecimalToIDAlphabet(&output);
return output;
}
std::string GenerateIdForPath(const base::FilePath& path) {
base::FilePath new_path = MaybeNormalizePath(path);
std::string path_bytes =
std::string(reinterpret_cast<const char*>(new_path.value().data()),
new_path.value().size() * sizeof(base::FilePath::CharType));
return GenerateId(path_bytes);
}
base::FilePath MaybeNormalizePath(const base::FilePath& path) {
#if defined(OS_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] == ':')
path_str[0] += ('A' - 'a');
return base::FilePath(path_str);
#else
return path;
#endif
}
}
}