[email protected] | 94d557e | 2010-06-23 21:41:40 | [diff] [blame] | 1 | // Copyright (c) 2010 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 "base/sha1.h" |
| 6 | |
| 7 | #include <windows.h> |
| 8 | #include <wincrypt.h> |
| 9 | |
[email protected] | 08ce4d4 | 2010-10-21 00:31:19 | [diff] [blame^] | 10 | #include "base/crypto/scoped_capi_types.h" |
[email protected] | 94d557e | 2010-06-23 21:41:40 | [diff] [blame] | 11 | #include "base/logging.h" |
[email protected] | 94d557e | 2010-06-23 21:41:40 | [diff] [blame] | 12 | |
| 13 | namespace base { |
| 14 | |
[email protected] | 94d557e | 2010-06-23 21:41:40 | [diff] [blame] | 15 | std::string SHA1HashString(const std::string& str) { |
[email protected] | 08ce4d4 | 2010-10-21 00:31:19 | [diff] [blame^] | 16 | ScopedHCRYPTPROV provider; |
| 17 | if (!CryptAcquireContext(provider.receive(), NULL, NULL, PROV_RSA_FULL, |
| 18 | CRYPT_VERIFYCONTEXT)) { |
| 19 | LOG(ERROR) << "CryptAcquireContext failed: " << GetLastError(); |
| 20 | return std::string(SHA1_LENGTH, '\0'); |
| 21 | } |
| 22 | |
| 23 | { |
| 24 | ScopedHCRYPTHASH hash; |
| 25 | if (!CryptCreateHash(provider, CALG_SHA1, 0, 0, hash.receive())) { |
| 26 | LOG(ERROR) << "CryptCreateHash failed: " << GetLastError(); |
| 27 | return std::string(SHA1_LENGTH, '\0'); |
| 28 | } |
| 29 | |
| 30 | if (!CryptHashData(hash, reinterpret_cast<CONST BYTE*>(str.data()), |
| 31 | static_cast<DWORD>(str.length()), 0)) { |
| 32 | LOG(ERROR) << "CryptHashData failed: " << GetLastError(); |
| 33 | return std::string(SHA1_LENGTH, '\0'); |
| 34 | } |
| 35 | |
| 36 | DWORD hash_len = 0; |
| 37 | DWORD buffer_size = sizeof hash_len; |
| 38 | if (!CryptGetHashParam(hash, HP_HASHSIZE, |
| 39 | reinterpret_cast<unsigned char*>(&hash_len), |
| 40 | &buffer_size, 0)) { |
| 41 | LOG(ERROR) << "CryptGetHashParam(HP_HASHSIZE) failed: " << GetLastError(); |
| 42 | return std::string(SHA1_LENGTH, '\0'); |
| 43 | } |
| 44 | |
| 45 | std::string result; |
| 46 | if (!CryptGetHashParam(hash, HP_HASHVAL, |
| 47 | // We need the + 1 here not because the call will write a trailing \0, |
| 48 | // but so that result.length() is correctly set to |hash_len|. |
| 49 | reinterpret_cast<BYTE*>(WriteInto(&result, hash_len + 1)), &hash_len, |
| 50 | 0))) { |
| 51 | LOG(ERROR) << "CryptGetHashParam(HP_HASHVAL) failed: " << GetLastError(); |
| 52 | return std::string(SHA1_LENGTH, '\0'); |
| 53 | } |
| 54 | |
| 55 | if (hash_len != SHA1_LENGTH) { |
| 56 | LOG(ERROR) << "Returned hash value is wrong length: " << hash_len |
| 57 | << " should be " << SHA1_LENGTH; |
| 58 | return std::string(SHA1_LENGTH, '\0'); |
| 59 | } |
| 60 | |
| 61 | return result; |
| 62 | } |
[email protected] | 94d557e | 2010-06-23 21:41:40 | [diff] [blame] | 63 | } |
| 64 | |
| 65 | } // namespace base |