source: rtems/c/src/lib/libbsp/shared/getentropy-cpucounter.c @ 3d374d9

5
Last change on this file since 3d374d9 was 3d374d9, checked in by Sebastian Huber <sebastian.huber@…>, on 11/17/17 at 08:43:17

bsps: Use a state in default getentropy()

Use the boot time to initialize the state. Use the state, the current
CPU counter and a very simple pseudo random number generator for
getentropy(). At least, this enables to pass the test "GETENTROPY 1" on
ERC32.

Update #3239.

  • Property mode set to 100644
File size: 1.4 KB
Line 
1/*
2 * Copyright (c) 2017 embedded brains GmbH.  All rights reserved.
3 *
4 *  embedded brains GmbH
5 *  Dornierstr. 4
6 *  82178 Puchheim
7 *  Germany
8 *  <rtems@embedded-brains.de>
9 *
10 * The license and distribution terms for this file may be
11 * found in the file LICENSE in this distribution or at
12 * http://www.rtems.org/license/LICENSE.
13 */
14
15/*
16 * ATTENTION: THIS IS A VERY LIMITED ENTROPY SOURCE.
17 *
18 * This implementation uses a time-based value for it's entropy. The only thing
19 * that makes it random are interrupts from external sources. Don't use it if
20 * you need for example a strong crypto.
21 */
22
23#include <sys/param.h>
24#include <unistd.h>
25#include <string.h>
26#include <rtems/bsd.h>
27#include <rtems/counter.h>
28#include <rtems/sysinit.h>
29
30static uint32_t state;
31
32int getentropy(void *ptr, size_t n)
33{
34  uint8_t *dest = ptr;
35
36  state ^= rtems_counter_read();
37  state *= 25169206;
38  state += 1679610226;
39
40  while (n > 0) {
41    size_t m;
42
43    m = MIN(n, sizeof(state));
44    memcpy(dest, &state, m);
45    n -= m;
46    dest += m;
47    state *= 85236167;
48    state += 30557471;
49  }
50
51  return 0;
52}
53
54static void getentropy_init(void)
55{
56  struct bintime bt;
57
58  rtems_bsd_bintime(&bt);
59  state = (uint32_t) bt.frac;
60  state ^= (uint32_t) (bt.frac >> 32);
61  state ^= (uint32_t) bt.sec;
62  state ^= (uint32_t) (bt.sec >> 32);
63}
64
65RTEMS_SYSINIT_ITEM(
66  getentropy_init,
67  RTEMS_SYSINIT_DEVICE_DRIVERS,
68  RTEMS_SYSINIT_ORDER_LAST
69);
Note: See TracBrowser for help on using the repository browser.