helpfor studient

Dependents:   STM32_F103-C8T6basecanblink_led

Fork of mbed-dev by mbed official

Revision:
180:b0033dcd6934
Parent:
163:74e0ce7f98e8
Child:
181:96ed750bd169
--- a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c	Thu Nov 23 11:57:25 2017 +0000
+++ b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c	Thu Dec 07 14:01:42 2017 +0000
@@ -30,9 +30,17 @@
 /*
  * Get Random number generator.
  */
+
+#define PRNG_KEY_SIZE  (0x20UL)
+
 static volatile int  g_PRNG_done;
 volatile int  g_AES_done;
 
+/* Implementation that should never be optimized out by the compiler */
+static void trng_zeroize( void *v, size_t n ) {
+    volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
+}
+
 void CRYPTO_IRQHandler()
 {
     if (PRNG_GET_INT_FLAG()) {
@@ -82,21 +90,22 @@
 int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length)
 {
     (void)obj;
-
-    *output_length = 0;
-    if (length < 32) {
-        unsigned char tmpBuff[32];
+    unsigned char tmpBuff[PRNG_KEY_SIZE];
+    size_t cur_length = 0;
+    
+    while (length >= sizeof(tmpBuff)) {
+        trng_get(output);
+        output += sizeof(tmpBuff);
+        cur_length += sizeof(tmpBuff);
+        length -= sizeof(tmpBuff);
+    }
+    if (length > 0) {
         trng_get(tmpBuff);
-        memcpy(output, &tmpBuff, length);
-        *output_length = length;
-    } else {
-        for (int i = 0; i < (length/32); i++) {
-            trng_get(output);
-            *output_length += 32;
-            output += 32;
-        }
+        memcpy(output, tmpBuff, length);
+        cur_length += length;
+        trng_zeroize(tmpBuff, sizeof(tmpBuff));
     }
-
+    *output_length = cur_length;
     return 0;
 }