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 "chrome/browser/sync/util/crypto_helpers.h" 6 7 #include <string> 8 #include <vector> 9 10 #include "base/basictypes.h" 11 #include "base/format_macros.h" 12 #include "base/logging.h" 13 #include "base/base64.h" 14 #include "base/rand_util.h" 15 #include "base/string_number_conversions.h" 16 #include "base/string_util.h" 17 18 using std::string; 19 using std::vector; 20 21 MD5Calculator::MD5Calculator() { 22 MD5Init(&context_); 23 } 24 25 MD5Calculator::~MD5Calculator() {} 26 27 void MD5Calculator::AddData(const unsigned char* data, int length) { 28 CHECK(bin_digest_.empty()); 29 MD5Update(&context_, data, length); 30 } 31 32 void MD5Calculator::CalcDigest() { 33 if (bin_digest_.empty()) { 34 MD5Digest digest; 35 MD5Final(&digest, &context_); 36 bin_digest_.assign(digest.a, digest.a + arraysize(digest.a)); 37 } 38 } 39 40 const vector<uint8>& MD5Calculator::GetDigest() { 41 CalcDigest(); 42 return bin_digest_; 43 } 44 45 std::string MD5Calculator::GetHexDigest() { 46 CalcDigest(); 47 string hex = base::HexEncode(reinterpret_cast<char*>(&bin_digest_.front()), 48 bin_digest_.size()); 49 StringToLowerASCII(&hex); 50 return hex; 51 } 52 53 void GetRandomBytes(char* output, int output_length) { 54 uint64 random_int; 55 const char* random_int_bytes = reinterpret_cast<const char*>(&random_int); 56 int random_int_size = sizeof(random_int); 57 for (int i = 0; i < output_length; i += random_int_size) { 58 random_int = base::RandUint64(); 59 int copy_count = std::min(output_length - i, random_int_size); 60 memcpy(output + i, random_int_bytes, copy_count); 61 } 62 } 63 64 string Generate128BitRandomHexString() { 65 const int kNumberBytes = 128 / 8; 66 std::string random_bytes(kNumberBytes, ' '); 67 GetRandomBytes(&random_bytes[0], kNumberBytes); 68 std::string base64_encoded_bytes; 69 base::Base64Encode(random_bytes, &base64_encoded_bytes); 70 return base64_encoded_bytes; 71 } 72