1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

nRF52でよく使用している乱数生成

Last updated at Posted at 2021-07-17

記事の概要

乱数を利用する方法について自分用のメモです。
詳しい解説はせず、コードのみの掲載になります。
もしも詳細を知りたい方がいるようならば説明させていただきたく、コメント欄にご記入ください。

ダミー乱数生成

乱数にみせかけたダミーの固定された数字列を生成します。
デバッグ時に生成鍵を固定値にしたい場合に使用します。

int entropy_dummy_source( void *data, unsigned char *output,
                                 size_t len, size_t *olen )
{
    ((void) data);

    memset( output, 0x6a, len );
    *olen = len;

    return( 0 );
}

乱数生成

# define CACHE_SIZE 32
static uint8_t cache[CACHE_SIZE] = {60};
static size_t cache_idx = 0;
static uint8_t rng_generate_uint8() {
    // Find out whether random data is available in the pool.
    uint8_t available;
    sd_rand_application_bytes_available_get(&available);

    if (available > 0) {
        // Generate a new random number and save it in the cache.
        const ret_code_t result = sd_rand_application_vector_get(cache + cache_idx, 1);
        APP_ERROR_CHECK(result);
    }

    // Return a number from the cache.
    const uint8_t ret = cache[cache_idx];
    cache_idx = (cache_idx + 1) % CACHE_SIZE;
    return ret;
}

static void generate_random(uint8_t *output, uint16_t output_len)
{
    nrf_delay_ms(10);
    for(int i=0;  i<output_len; i++)
    {
        *(output+i) = rng_generate_uint8();
    }
}

int entropy_source( void *data, unsigned char *output,
                                 size_t len, size_t *olen )
{
    ((void) data);

    generate_random(output, len);
    *olen = len;

    return( 0 );
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?