| 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 <algorithm> | 7 #include <algorithm> |
| 8 | 8 |
| 9 #include "base/logging.h" | 9 #include "base/logging.h" |
| 10 #include "crypto/secure_memcmp.h" |
| 10 | 11 |
| 11 namespace crypto { | 12 namespace crypto { |
| 12 | 13 |
| 13 // Performs a constant-time comparison of two strings, returning true if the | |
| 14 // strings are equal. | |
| 15 // | |
| 16 // For cryptographic operations, comparison functions such as memcmp() may | |
| 17 // expose side-channel information about input, allowing an attacker to | |
| 18 // perform timing analysis to determine what the expected bits should be. In | |
| 19 // order to avoid such attacks, the comparison must execute in constant time, | |
| 20 // so as to not to reveal to the attacker where the difference(s) are. | |
| 21 // For an example attack, see | |
| 22 // http://groups.google.com/group/keyczar-discuss/browse_thread/thread/5571eca09
48b2a13 | |
| 23 static bool SecureMemcmp(const void* s1, const void* s2, size_t n) { | |
| 24 const unsigned char* s1_ptr = reinterpret_cast<const unsigned char*>(s1); | |
| 25 const unsigned char* s2_ptr = reinterpret_cast<const unsigned char*>(s2); | |
| 26 unsigned char tmp = 0; | |
| 27 for (size_t i = 0; i < n; ++i, ++s1_ptr, ++s2_ptr) | |
| 28 tmp |= *s1_ptr ^ *s2_ptr; | |
| 29 return (tmp == 0); | |
| 30 } | |
| 31 | |
| 32 size_t HMAC::DigestLength() const { | 14 size_t HMAC::DigestLength() const { |
| 33 switch (hash_alg_) { | 15 switch (hash_alg_) { |
| 34 case SHA1: | 16 case SHA1: |
| 35 return 20; | 17 return 20; |
| 36 case SHA256: | 18 case SHA256: |
| 37 return 32; | 19 return 32; |
| 38 default: | 20 default: |
| 39 NOTREACHED(); | 21 NOTREACHED(); |
| 40 return 0; | 22 return 0; |
| 41 } | 23 } |
| (...skipping 14 matching lines...) Expand all Loading... |
| 56 scoped_array<unsigned char> computed_digest( | 38 scoped_array<unsigned char> computed_digest( |
| 57 new unsigned char[digest_length]); | 39 new unsigned char[digest_length]); |
| 58 if (!Sign(data, computed_digest.get(), static_cast<int>(digest_length))) | 40 if (!Sign(data, computed_digest.get(), static_cast<int>(digest_length))) |
| 59 return false; | 41 return false; |
| 60 | 42 |
| 61 return SecureMemcmp(digest.data(), computed_digest.get(), | 43 return SecureMemcmp(digest.data(), computed_digest.get(), |
| 62 std::min(digest.size(), digest_length)); | 44 std::min(digest.size(), digest_length)); |
| 63 } | 45 } |
| 64 | 46 |
| 65 } // namespace crypto | 47 } // namespace crypto |
| OLD | NEW |