ARMmbed / mbed-os

Arm Mbed OS is a platform operating system designed for the internet of things
https://mbed.com
Other
4.68k stars 2.98k forks source link

TRNG support for nRF5x devices #4588

Closed HITMAnsOFT closed 6 years ago

HITMAnsOFT commented 7 years ago

I am working on a BLE-based car alarm using nRF52832, and I need secure random key generation for a custom communication protocol. The nRF51x and nRF52x devices all contain a hardware RNG core, and the HAL and drivers are available in the Nordic SDK. However, the mbed OS doesn't seem to support trng_api for Nordic targets. I tried to directly call the Nordic HAL methods, but I found out that the corresponding files are missing from the TARGET_SDK11 folder. Those files (drivers_nrf/hal/nrf_rng.h, drivers_nrf/rng/nrf_drv_rng.h, drivers_nrf/rng/nrf_drv_rng.c) do exist in the TARGET_SDK13 folder, but for some reason it is not used with the nRF52832 device.

It would be nice to support TRNG HAL for nRF51 and nRF52 devices.

pan- commented 7 years ago

@nvlsianpu

HITMAnsOFT commented 7 years ago

Update: I downloaded the Nordic SDK version 11 and copied the HAL and driver files mentioned above into my project source dir and was able to use the RNG module directly.

nvlsianpu commented 7 years ago

@nvlsianpu have You a POC for look at?

HITMAnsOFT commented 7 years ago

@nvlsianpu I have this small C++ wrapper. It may not be robust and may cause an infinite loop, but it's working for me on nRF52832. The buffer depth of the RNG seems to be 32 bytes:

#include "nrf_drv_rng.h"

class Random {
public:
    Random ()
    {
        nrf_drv_rng_init(nullptr);
    }

    template <class T, size_t size> void getArray(std::array<T, size>& out)
    {
        for (T& a : out) {
            uint8_t available = 0;
            do {
                nrf_drv_rng_bytes_available(&available);
            } while (available < sizeof(T));
            nrf_drv_rng_rand(&a, sizeof(T)); 
        }
    }
};
nvlsianpu commented 7 years ago

Thanks for the snipped. I wanted to know whether rng driver work out-off-the-box for nRF52. So answer is yes.

HITMAnsOFT commented 7 years ago

Yes, it works. Chip code is QFAA B0. Unfortunately I was not able to run my applicaiton on nRF51. Do you happen to know if mbed works on Rev. 2 nRF51822 chips?

nvlsianpu commented 7 years ago

mbed-os apps are supposed to work since rev. 3 of nRF51822. I never tested it with rev. 2

HITMAnsOFT commented 7 years ago

I've ordered a couple of what seems to be Rev 3 nRF51822 modules. Will test this code on them when I get them.

dlfryar-zz commented 6 years ago

Mbed OS SDK updates happening here

marcuschangarm commented 6 years ago

New TRNG driver has been merged to master: https://github.com/ARMmbed/mbed-os/pull/6116