xref: /OK3568_Linux_fs/external/security/librkcrypto/test/test_random.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /*
2  * Copyright (c) 2022 Rockchip Electronics Co. Ltd.
3  */
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include "rkcrypto_random.h"
8 
9 #define RAND_MAX_LEN	1024 * 1024
10 
hamming_weight8(uint8_t w)11 static unsigned int hamming_weight8(uint8_t w)
12 {
13 	unsigned int res = w - ((w >> 1) & 0x55);
14 	res = (res & 0x33) + ((res >> 2) & 0x33);
15 	return (res + (res >> 4)) & 0x0F;
16 }
17 
test_random(void)18 RK_RES test_random(void)
19 {
20 	uint32_t len, hw, i;
21 	uint8_t data[RAND_MAX_LEN];
22 
23 	for (len = 8; len <= RAND_MAX_LEN; len *= 2) {
24 		if (rk_get_random(data, len))
25 			goto error;
26 
27 		hw = 0;
28 		for (i = 0; i < len; i++) {
29 			hw += hamming_weight8(data[i]);
30 		}
31 
32 		/*
33 		 * With sufficient length (>= 8 bytes), the hamming weight of
34 		 * every 8 bits should stay between 1 and 7 on average.
35 		 */
36 		if (hw < len || hw > (len * 8 - len)) {
37 			printf("Get random %d bits, hamming_weight is %d.\n", len * 8, hw);
38 			goto error;
39 		}
40 	}
41 
42 	printf("TEST get random function SUCCESS.\n");
43 	printf("NOTE: Testing for calling rk_get_random API. No testing for randomness/unpredictability.\n");
44 	return RK_CRYPTO_SUCCESS;
45 error:
46 	printf("TEST get random function FAILED!!!\n");
47 	return RK_CRYPTO_ERR_GENERIC;
48 }
49