1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/crx_file/id_util.h"
7 #include "base/files/file_path.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/string_util.h"
11 #include "crypto/sha2.h"
15 // Converts a normal hexadecimal string into the alphabet used by extensions.
16 // We use the characters 'a'-'p' instead of '0'-'f' to avoid ever having a
17 // completely numeric host, since some software interprets that as an IP
19 static void ConvertHexadecimalToIDAlphabet(std::string
* id
) {
20 for (size_t i
= 0; i
< id
->size(); ++i
) {
22 if (base::HexStringToInt(
23 base::StringPiece(id
->begin() + i
, id
->begin() + i
+ 1), &val
)) {
36 // First 16 bytes of SHA256 hashed public key.
37 const size_t kIdSize
= 16;
39 std::string
GenerateId(const std::string
& input
) {
41 crypto::SHA256HashString(input
, hash
, sizeof(hash
));
43 base::StringToLowerASCII(base::HexEncode(hash
, sizeof(hash
)));
44 ConvertHexadecimalToIDAlphabet(&output
);
49 std::string
GenerateIdForPath(const base::FilePath
& path
) {
50 base::FilePath new_path
= MaybeNormalizePath(path
);
51 std::string path_bytes
=
52 std::string(reinterpret_cast<const char*>(new_path
.value().data()),
53 new_path
.value().size() * sizeof(base::FilePath::CharType
));
54 return GenerateId(path_bytes
);
57 std::string
HashedIdInHex(const std::string
& id
) {
58 const std::string id_hash
= base::SHA1HashString(id
);
59 DCHECK_EQ(base::kSHA1Length
, id_hash
.length());
60 return base::HexEncode(id_hash
.c_str(), id_hash
.length());
63 base::FilePath
MaybeNormalizePath(const base::FilePath
& path
) {
65 // Normalize any drive letter to upper-case. We do this for consistency with
66 // net_utils::FilePathToFileURL(), which does the same thing, to make string
67 // comparisons simpler.
68 base::FilePath::StringType path_str
= path
.value();
69 if (path_str
.size() >= 2 && path_str
[0] >= L
'a' && path_str
[0] <= L
'z' &&
71 path_str
[0] = towupper(path_str
[0]);
73 return base::FilePath(path_str
);
79 bool IdIsValid(const std::string
& id
) {
80 // Verify that the id is legal.
81 if (id
.size() != (crx_file::id_util::kIdSize
* 2))
84 // We only support lowercase IDs, because IDs can be used as URL components
85 // (where GURL will lowercase it).
86 std::string temp
= base::StringToLowerASCII(id
);
87 for (size_t i
= 0; i
< temp
.size(); i
++)
88 if (temp
[i
] < 'a' || temp
[i
] > 'p')
94 } // namespace id_util
95 } // namespace crx_file