44a7eb42fbd1acc86ed269ad7fbe13f93d3b6d66
[platform/framework/web/crosswalk.git] / src / xwalk / application / common / id_util.cc
1 // Copyright (c) 2013 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.
4
5 #include "xwalk/application/common/id_util.h"
6
7 #include "base/files/file_path.h"
8 #include "base/strings/string_util.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "crypto/sha2.h"
11
12 namespace xwalk {
13 namespace application {
14
15 // Converts a normal hexadecimal string into the alphabet used by applications.
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
18 // address.
19 static void ConvertHexadecimalToIDAlphabet(std::string* id) {
20   for (size_t i = 0; i < id->size(); ++i) {
21     int val;
22     if (base::HexStringToInt(base::StringPiece(
23             id->begin() + i, id->begin() + i + 1), &val)) {
24       (*id)[i] = val + 'a';
25     } else {
26       (*id)[i] = 'a';
27     }
28   }
29 }
30
31 // First 16 bytes of SHA256 hashed public key.
32 const size_t kIdSize = 16;
33
34 #if defined(OS_TIZEN)
35 const size_t kLegacyTizenIdSize = 10;
36 #endif
37
38 std::string GenerateId(const std::string& input) {
39   uint8 hash[kIdSize];
40   crypto::SHA256HashString(input, hash, sizeof(hash));
41   std::string output = StringToLowerASCII(base::HexEncode(hash, sizeof(hash)));
42   ConvertHexadecimalToIDAlphabet(&output);
43
44   return output;
45 }
46
47 std::string GenerateIdForPath(const base::FilePath& path) {
48   std::string path_bytes =
49       std::string(reinterpret_cast<const char*>(path.value().data()),
50                   path.value().size() * sizeof(base::FilePath::CharType));
51   return GenerateId(path_bytes);
52 }
53
54 }  // namespace application
55 }  // namespace xwalk