OLD | NEW |
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "crypto/hmac.h" | 5 #include "crypto/hmac.h" |
6 | 6 |
7 #include "base/logging.h" | 7 #include "base/logging.h" |
8 | 8 |
9 namespace crypto { | 9 namespace crypto { |
10 | 10 |
| 11 // Performs a constant-time comparison of two strings, returning true if the |
| 12 // strings are equal. |
| 13 // |
| 14 // For cryptographic operations, comparison functions such as memcmp() may |
| 15 // expose side-channel information about input, allowing an attacker to |
| 16 // perform timing analysis to determine what the expected bits should be. In |
| 17 // order to avoid such attacks, the comparison must execute in constant time, |
| 18 // so as to not to reveal to the attacker where the difference(s) are. |
| 19 // For an example attack, see |
| 20 // http://groups.google.com/group/keyczar-discuss/browse_thread/thread/5571eca09
48b2a13 |
| 21 static bool SecureMemcmp(const void* s1, const void* s2, size_t n) { |
| 22 const unsigned char* s1_ptr = reinterpret_cast<const unsigned char*>(s1); |
| 23 const unsigned char* s2_ptr = reinterpret_cast<const unsigned char*>(s2); |
| 24 unsigned char tmp = 0; |
| 25 for (size_t i = 0; i < n; ++i, ++s1_ptr, ++s2_ptr) |
| 26 tmp |= *s1_ptr ^ *s2_ptr; |
| 27 return (tmp == 0); |
| 28 } |
| 29 |
11 size_t HMAC::DigestLength() const { | 30 size_t HMAC::DigestLength() const { |
12 switch (hash_alg_) { | 31 switch (hash_alg_) { |
13 case SHA1: | 32 case SHA1: |
14 return 20; | 33 return 20; |
15 case SHA256: | 34 case SHA256: |
16 return 32; | 35 return 32; |
17 default: | 36 default: |
18 NOTREACHED(); | 37 NOTREACHED(); |
19 return 0; | 38 return 0; |
20 } | 39 } |
21 } | 40 } |
22 | 41 |
| 42 bool HMAC::Verify(const base::StringPiece& data, |
| 43 const base::StringPiece& digest) const { |
| 44 if (digest.size() != DigestLength()) |
| 45 return false; |
| 46 scoped_array<unsigned char> computed_digest( |
| 47 new unsigned char[digest.size()]); |
| 48 if (!Sign(data, computed_digest.get(), static_cast<int>(digest.size()))) |
| 49 return false; |
| 50 |
| 51 return SecureMemcmp(digest.data(), computed_digest.get(), digest.size()); |
| 52 } |
| 53 |
23 } // namespace crypto | 54 } // namespace crypto |
OLD | NEW |