blob: 853c2441587d303352271f04f70de9b9b921c284 [file] [log] [blame]
[email protected]94d557e2010-06-23 21:41:401// 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]08ce4d42010-10-21 00:31:1910#include "base/crypto/scoped_capi_types.h"
[email protected]94d557e2010-06-23 21:41:4011#include "base/logging.h"
[email protected]94d557e2010-06-23 21:41:4012
13namespace base {
14
[email protected]94d557e2010-06-23 21:41:4015std::string SHA1HashString(const std::string& str) {
[email protected]08ce4d42010-10-21 00:31:1916 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]94d557e2010-06-23 21:41:4063}
64
65} // namespace base