1 /* 2 * Copyright 2014-2022 The GmSSL Project. All Rights Reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the License); you may 5 * not use this file except in compliance with the License. 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 */ 9 10 11 12 #include <stdio.h> 13 #include <string.h> 14 #include <stdlib.h> 15 #include <gmssl/rand.h> 16 #include <gmssl/error.h> 17 18 #define RAND_MAX_BUF_SIZE 4096 19 rand_bytes(uint8_t * buf,size_t len)20int rand_bytes(uint8_t *buf, size_t len) 21 { 22 FILE *fp; 23 if (!buf) { 24 error_print(); 25 return -1; 26 } 27 if (len > RAND_MAX_BUF_SIZE) { 28 error_print(); 29 return -1; 30 } 31 if (!len) { 32 return 0; 33 } 34 35 if (!(fp = fopen("/dev/urandom", "rb"))) { 36 error_print(); 37 return -1; 38 } 39 if (fread(buf, 1, len, fp) != len) { 40 error_print(); 41 fclose(fp); 42 return -1; 43 } 44 fclose(fp); 45 return 1; 46 } 47