1 /* prng.h -- Pseudo Random Numbers
2  *
3  * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the library tinydtls. Please see
6  * README for terms of use.
7  */
8 
9 /**
10  * @file prng.h
11  * @brief Pseudo Random Numbers
12  */
13 
14 #ifndef _DTLS_PRNG_H_
15 #define _DTLS_PRNG_H_
16 
17 #include "tinydtls.h"
18 
19 /**
20  * @defgroup prng Pseudo Random Numbers
21  * @{
22  */
23 
24 #ifndef WITH_CONTIKI
25 #include <stdlib.h>
26 
27 /**
28  * Fills \p buf with \p len random bytes. This is the default
29  * implementation for prng().  You might want to change prng() to use
30  * a better PRNG on your specific platform.
31  */
32 static inline int
dtls_prng(unsigned char * buf,size_t len)33 dtls_prng(unsigned char *buf, size_t len) {
34   while (len--)
35     *buf++ = rand() & 0xFF;
36   return 1;
37 }
38 
39 static inline void
dtls_prng_init(unsigned short seed)40 dtls_prng_init(unsigned short seed) {
41 	srand(seed);
42 }
43 #else /* WITH_CONTIKI */
44 #include <string.h>
45 #include "random.h"
46 
47 #ifdef HAVE_PRNG
48 static inline int
dtls_prng(unsigned char * buf,size_t len)49 dtls_prng(unsigned char *buf, size_t len)
50 {
51 	return contiki_prng_impl(buf, len);
52 }
53 #else
54 /**
55  * Fills \p buf with \p len random bytes. This is the default
56  * implementation for prng().  You might want to change prng() to use
57  * a better PRNG on your specific platform.
58  */
59 static inline int
dtls_prng(unsigned char * buf,size_t len)60 dtls_prng(unsigned char *buf, size_t len) {
61   unsigned short v = random_rand();
62   while (len > sizeof(v)) {
63     memcpy(buf, &v, sizeof(v));
64     len -= sizeof(v);
65     buf += sizeof(v);
66     v = random_rand();
67   }
68 
69   memcpy(buf, &v, len);
70   return 1;
71 }
72 #endif /* HAVE_PRNG */
73 
74 static inline void
dtls_prng_init(unsigned short seed)75 dtls_prng_init(unsigned short seed) {
76   /* random_init() messes with the radio interface of the CC2538 and
77    * therefore must not be called after the radio has been
78    * initialized. */
79 #ifndef CONTIKI_TARGET_CC2538DK
80 	random_init(seed);
81 #endif
82 }
83 #endif /* WITH_CONTIKI */
84 
85 /** @} */
86 
87 #endif /* _DTLS_PRNG_H_ */
88