~aleteoryx/muditaos

ref: 6b45d3b71dc1e09a16a3bc66cc54ced1c9de8d43 muditaos/module-bsp/board/rt1051/bsp/trng/RT1051Trng.cpp -rw-r--r-- 1.5 KiB
6b45d3b7 — Maciej Gibowicz [BH-2097] Adding and deleting a single custom quote 1 year, 8 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// Copyright (c) 2017-2024, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/blob/master/LICENSE.md

#include "RT1051Trng.hpp"
#include <log/log.hpp>

namespace bsp
{
    namespace
    {
        constexpr auto trngMaxFrequencyCountLimit = 0x3FFFE;
    }

    RT1051Trng::result_type RT1051Trng::generateRandomNumber()
    {
        status_t status;
        trng_config_t trngConfig{};
        RT1051Trng::result_type result;

        /* Default config is very slow, but creates entropy of very high quality */
        status = TRNG_GetDefaultConfig(&trngConfig);
        if (status != kStatus_Success) {
            LOG_FATAL("Failed to get TRNG default config, error: %" PRIi32, status);
            return max();
        }

        /* Use von Neumann sampling for better randomness */
        trngConfig.sampleMode = kTRNG_SampleModeVonNeumann;
        /* Default value is too small what causes TRNG to fail often */
        trngConfig.frequencyCountLimit.maximum = trngMaxFrequencyCountLimit;

        status = TRNG_Init(TRNG, &trngConfig);
        if (status != kStatus_Success) {
            LOG_FATAL("Failed to initialize TRNG module, error: %" PRIi32, status);
            return max();
        }

        status = TRNG_GetRandomData(TRNG, static_cast<void *>(&result), sizeof(result));
        if (status != kStatus_Success) {
            LOG_FATAL("Failed to get random value, error: %" PRIi32, status);
            return max();
        }

        TRNG_Deinit(TRNG);

        return result;
    }
}; // namespace bsp