Chromium Code Reviews| Index: crypto/random.cc |
| diff --git a/crypto/random.cc b/crypto/random.cc |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..2165399631826e3bf54b149367b40e15d4ce5879 |
| --- /dev/null |
| +++ b/crypto/random.cc |
| @@ -0,0 +1,47 @@ |
| +// Copyright (c) 2011 The Chromium Authors. All rights reserved. |
| +// Use of this source code is governed by a BSD-style license that can be |
| +// found in the LICENSE file. |
| + |
| +#include "crypto/random.h" |
| + |
| +#include <string> |
| + |
| +#if defined(OS_WIN) |
| +#include "crypto/scoped_capi_types.h" |
| +#endif // defined(OS_WIN) |
|
wtc
2011/04/28 19:42:22
Nit: this block should be moved after line 14. Se
|
| + |
| +#include "base/base64.h" |
| +#include "base/rand_util.h" |
| + |
| +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
|
| +#if defined(OS_WIN) |
|
wtc
2011/04/28 19:42:22
Optional: I would just eliminate the OS_WIN code.
|
| + ScopedHCRYPTPROV safe_provider; |
| + // Note: The only time NULL is safe to be passed as pszContainer is when |
| + // dwFlags contains CRYPT_VERIFYCONTEXT, as all keys generated and/or used |
| + // will be treated as ephemeral keys and not persisted. |
| + BOOL ok = CryptAcquireContext(safe_provider.receive(), NULL, NULL, |
| + PROV_RSA_AES, CRYPT_VERIFYCONTEXT); |
|
Ryan Sleevi
2011/04/27 02:32:24
drive by: PROV_RSA_AES is only valid for XP SP2+.
|
| + if (!ok) |
| + return; |
| + |
| + CryptGenRandom(safe_provider, output_length, output); |
|
Ryan Sleevi
2011/04/27 02:32:24
nit: I know the style guide recommends size_t for
|
| +#else |
| + uint64 random_int; |
| + const char* random_int_bytes = reinterpret_cast<const char*>(&random_int); |
| + size_t random_int_size = sizeof(random_int); |
| + for (size_t i = 0; i < output_length; i += random_int_size) { |
| + random_int = base::RandUint64(); |
| + size_t copy_count = std::min(output_length - i, random_int_size); |
| + memcpy(((uint8*)output) + i, random_int_bytes, copy_count); |
| + } |
| +#endif // defined(OS_WIN) |
| +} |
| + |
| +std::string Generate128BitRandomBase64String() { |
| + const int kNumberBytes = 128 / 8; |
| + std::string random_bytes(kNumberBytes, ' '); |
| + GetRandomBytes(&random_bytes[0], kNumberBytes); |
| + std::string base64_encoded_bytes; |
| + base::Base64Encode(random_bytes, &base64_encoded_bytes); |
| + return base64_encoded_bytes; |
| +} |