xref: /aosp_15_r20/external/openscreen/util/crypto/random_bytes_unittest.cc (revision 3f982cf4871df8771c9d4abe6e9a6f8d829b2736)
1 // Copyright 2020 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 "util/crypto/random_bytes.h"
6 
7 #include <algorithm>
8 #include <utility>
9 
10 #include "gtest/gtest.h"
11 
12 namespace openscreen {
13 namespace {
14 
15 struct NonZero {
16   NonZero() = default;
operator ()openscreen::__anon46f9b8ff0111::NonZero17   bool operator()(int n) const { return n > 0; }
18 };
19 
20 }  // namespace
21 
TEST(RandomBytesTest,CanGenerateRandomBytes)22 TEST(RandomBytesTest, CanGenerateRandomBytes) {
23   std::array<uint8_t, 4> bytes;
24   GenerateRandomBytes(bytes.begin(), bytes.size());
25 
26   NonZero pred;
27   ASSERT_TRUE(std::any_of(bytes.begin(), bytes.end(), pred));
28 }
29 
TEST(RandomBytesTest,CanGenerate16RandomBytes)30 TEST(RandomBytesTest, CanGenerate16RandomBytes) {
31   std::array<uint8_t, 16> bytes = GenerateRandomBytes16();
32 
33   NonZero pred;
34   ASSERT_TRUE(std::any_of(bytes.begin(), bytes.end(), pred));
35 }
36 
TEST(RandomBytesTest,KeysAreNotIdentical)37 TEST(RandomBytesTest, KeysAreNotIdentical) {
38   constexpr int kNumKeys = 100;
39   constexpr int kKeyLength = 100;
40   std::array<std::array<uint8_t, kKeyLength>, kNumKeys> keys;
41   for (int i = 0; i < kNumKeys; ++i) {
42     GenerateRandomBytes(keys[i].begin(), kKeyLength);
43   }
44 
45   std::sort(std::begin(keys), std::end(keys));
46   ASSERT_TRUE(std::adjacent_find(std::begin(keys), std::end(keys)) ==
47               std::end(keys));
48 }
49 
50 }  // namespace openscreen
51