1 // Copyright 2024 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <zircon/assert.h> 17 #include <zircon/syscalls.h> 18 19 #include <climits> 20 21 #include "pw_random/random.h" 22 #include "pw_span/span.h" 23 24 namespace pw::random_fuchsia { 25 26 class ZirconRandomGenerator final : public pw::random::RandomGenerator { 27 public: Get(pw::ByteSpan dest)28 void Get(pw::ByteSpan dest) override { 29 zx_cprng_draw(dest.data(), dest.size()); 30 } 31 InjectEntropyBits(uint32_t data,uint_fast8_t num_bits)32 void InjectEntropyBits(uint32_t data, uint_fast8_t num_bits) override { 33 static_assert(sizeof(data) <= ZX_CPRNG_ADD_ENTROPY_MAX_LEN); 34 35 constexpr uint8_t max_bits = sizeof(data) * CHAR_BIT; 36 if (num_bits == 0) { 37 return; 38 } else if (num_bits > max_bits) { 39 num_bits = max_bits; 40 } 41 42 // zx_cprng_add_entropy operates on bytes instead of bits, so round up to 43 // the nearest byte so that all entropy bits are included. 44 const size_t buffer_size = ((num_bits + CHAR_BIT - 1) / CHAR_BIT); 45 zx_cprng_add_entropy(&data, buffer_size); 46 } 47 }; 48 49 } // namespace pw::random_fuchsia 50