Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 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 | |
| 3 // found in the LICENSE file. | |
| 4 | |
| 5 #include "crypto/random.h" | |
| 6 | |
| 7 #include <string> | |
| 8 | |
| 9 #if defined(OS_WIN) | |
| 10 #include "crypto/scoped_capi_types.h" | |
| 11 #endif // defined(OS_WIN) | |
|
wtc
2011/04/28 19:42:22
Nit: this block should be moved after line 14. Se
| |
| 12 | |
| 13 #include "base/base64.h" | |
| 14 #include "base/rand_util.h" | |
| 15 | |
| 16 void GetRandomBytes(void* output, size_t output_length) { | |
|
Ryan Sleevi
2011/04/27 02:32:24
nit: Should the return be a bool instead?
Both Cr
| |
| 17 #if defined(OS_WIN) | |
|
wtc
2011/04/28 19:42:22
Optional: I would just eliminate the OS_WIN code.
| |
| 18 ScopedHCRYPTPROV safe_provider; | |
| 19 // Note: The only time NULL is safe to be passed as pszContainer is when | |
| 20 // dwFlags contains CRYPT_VERIFYCONTEXT, as all keys generated and/or used | |
| 21 // will be treated as ephemeral keys and not persisted. | |
| 22 BOOL ok = CryptAcquireContext(safe_provider.receive(), NULL, NULL, | |
| 23 PROV_RSA_AES, CRYPT_VERIFYCONTEXT); | |
|
Ryan Sleevi
2011/04/27 02:32:24
drive by: PROV_RSA_AES is only valid for XP SP2+.
| |
| 24 if (!ok) | |
| 25 return; | |
| 26 | |
| 27 CryptGenRandom(safe_provider, output_length, output); | |
|
Ryan Sleevi
2011/04/27 02:32:24
nit: I know the style guide recommends size_t for
| |
| 28 #else | |
| 29 uint64 random_int; | |
| 30 const char* random_int_bytes = reinterpret_cast<const char*>(&random_int); | |
| 31 size_t random_int_size = sizeof(random_int); | |
| 32 for (size_t i = 0; i < output_length; i += random_int_size) { | |
| 33 random_int = base::RandUint64(); | |
| 34 size_t copy_count = std::min(output_length - i, random_int_size); | |
| 35 memcpy(((uint8*)output) + i, random_int_bytes, copy_count); | |
| 36 } | |
| 37 #endif // defined(OS_WIN) | |
| 38 } | |
| 39 | |
| 40 std::string Generate128BitRandomBase64String() { | |
| 41 const int kNumberBytes = 128 / 8; | |
| 42 std::string random_bytes(kNumberBytes, ' '); | |
| 43 GetRandomBytes(&random_bytes[0], kNumberBytes); | |
| 44 std::string base64_encoded_bytes; | |
| 45 base::Base64Encode(random_bytes, &base64_encoded_bytes); | |
| 46 return base64_encoded_bytes; | |
| 47 } | |
| OLD | NEW |