|
43 | 43 | #include <stdlib.h>
|
44 | 44 | #include <adi_rng.h>
|
45 | 45 | #include <adi_pwr.h>
|
| 46 | +#include "adi_rng_def.h" |
46 | 47 | #include "cmsis.h"
|
47 | 48 | #include "trng_api.h"
|
48 | 49 |
|
@@ -86,37 +87,48 @@ void trng_free(trng_t *obj)
|
86 | 87 | int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length)
|
87 | 88 | {
|
88 | 89 | ADI_RNG_HANDLE RNGhDevice = obj->RNGhDevice;
|
89 |
| - bool bRNGRdy; |
90 |
| - uint32_t nRandomNum, i; |
| 90 | + bool bRNGRdy, bStuck; |
| 91 | + uint32_t i; |
| 92 | + volatile uint32_t nRandomNum; |
91 | 93 | ADI_RNG_RESULT result;
|
| 94 | + ADI_RNG_DEV_TYPE *pDevice = (ADI_RNG_DEV_TYPE*)RNGhDevice; |
92 | 95 |
|
93 | 96 | for (i = 0; i < length; i++) {
|
94 | 97 | // Loop until the device has data to be read
|
95 | 98 | do {
|
96 | 99 | result = adi_rng_GetRdyStatus(RNGhDevice, &bRNGRdy);
|
97 |
| - if (result != ADI_RNG_SUCCESS) |
98 |
| - { |
| 100 | + if (result != ADI_RNG_SUCCESS) { |
99 | 101 | return -1;
|
100 | 102 | }
|
101 | 103 | } while (!bRNGRdy);
|
102 | 104 |
|
| 105 | + // Check the STUCK bit to make sure the oscillator output isn't stuck |
| 106 | + result = adi_rng_GetStuckStatus(RNGhDevice, &bStuck); |
| 107 | + |
| 108 | + // If the stuck bit is set, this means there may be a problem with RNG hardware, |
| 109 | + // exit with an error |
| 110 | + if ( (result != ADI_RNG_SUCCESS) || ((result == ADI_RNG_SUCCESS) && (bStuck)) ) { |
| 111 | + // Clear the STUCK bit by writing a 1 to it |
| 112 | + pDevice->pRNG->STAT |= BITM_RNG_STAT_STUCK; |
| 113 | + return -1; |
| 114 | + } |
| 115 | + |
103 | 116 | // Read the RNG
|
104 |
| - result = adi_rng_GetRngData(RNGhDevice, &nRandomNum); |
| 117 | + result = adi_rng_GetRngData(RNGhDevice, (uint32_t*)(&nRandomNum)); |
105 | 118 |
|
106 |
| - if (result != ADI_RNG_SUCCESS) |
107 |
| - { |
| 119 | + if (result != ADI_RNG_SUCCESS) { |
108 | 120 | return -1;
|
109 | 121 | }
|
110 | 122 |
|
111 | 123 | // Save the output
|
112 | 124 | output[i] = (uint8_t)(nRandomNum & 0xFF);
|
113 |
| - |
114 |
| - // Clear the nRandomNum variable for security purposes |
115 |
| - nRandomNum = 0; |
116 | 125 | }
|
117 | 126 |
|
118 | 127 | *output_length = length;
|
119 | 128 |
|
| 129 | + // Clear nRandomNum on the stack before exiting |
| 130 | + nRandomNum = 0; |
| 131 | + |
120 | 132 | return 0;
|
121 | 133 | }
|
122 | 134 |
|
|
0 commit comments