Avi Drissman | 201a9a83 | 2022-09-13 19:39:25 | [diff] [blame] | 1 | // Copyright 2012 The Chromium Authors |
mniknami@chromium.org | 9b20578 | 2012-08-02 20:22:25 | [diff] [blame] | 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 | |
avi | dd373b8b | 2015-12-21 21:34:43 | [diff] [blame] | 7 | #include<stddef.h> |
| 8 | |
Peter Kasting | 4cb72b5 | 2024-11-21 17:54:03 | [diff] [blame] | 9 | #include<algorithm> |
davidben | 6004dc5 | 2017-02-03 04:15:29 | [diff] [blame] | 10 | #include<string> |
| 11 | |
mniknami@chromium.org | 9b20578 | 2012-08-02 20:22:25 | [diff] [blame] | 12 | #include"testing/gtest/include/gtest/gtest.h" |
| 13 | |
| 14 | // Basic functionality tests. Does NOT test the security of the random data. |
| 15 | |
| 16 | // Ensures we don't have all trivial data, i.e. that the data is indeed random. |
| 17 | // Currently, that means the bytes cannot be all the same (e.g. all zeros). |
danakj | 95305d27 | 2024-05-09 20:38:44 | [diff] [blame] | 18 | boolIsTrivial(base::span<constuint8_t> bytes){ |
Peter Kasting | 4cb72b5 | 2024-11-21 17:54:03 | [diff] [blame] | 19 | constuint8_t first_byte= bytes.front(); |
| 20 | return std::ranges::all_of(bytes, |
| 21 | [=](uint8_t byte){return byte== first_byte;}); |
mniknami@chromium.org | 9b20578 | 2012-08-02 20:22:25 | [diff] [blame] | 22 | } |
| 23 | |
| 24 | TEST(RandBytes,RandBytes){ |
danakj | 95305d27 | 2024-05-09 20:38:44 | [diff] [blame] | 25 | std::array<uint8_t,16> bytes; |
| 26 | crypto::RandBytes(bytes); |
Tom Sepez | b0d0de60 | 2024-01-26 06:47:31 | [diff] [blame] | 27 | EXPECT_FALSE(IsTrivial(bytes)); |
| 28 | } |
| 29 | |
| 30 | TEST(RandBytes,RandBytesAsVector){ |
danakj | 95305d27 | 2024-05-09 20:38:44 | [diff] [blame] | 31 | std::vector<uint8_t>vector= crypto::RandBytesAsVector(16); |
| 32 | EXPECT_FALSE(IsTrivial(vector)); |
mniknami@chromium.org | 9b20578 | 2012-08-02 20:22:25 | [diff] [blame] | 33 | } |