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 #include <stdio.h> 12 #include <string.h> 13 #include <stdlib.h> 14 #include <gmssl/error.h> 15 #include <immintrin.h> 16 rdrand_bytes(uint8_t * buf,size_t buflen)17int rdrand_bytes(uint8_t *buf, size_t buflen) 18 { 19 uint64_t val; 20 uint8_t *p = (uint8_t *)&val; 21 22 while (buflen) { 23 size_t len = buflen >= sizeof(val) ? sizeof(val) : buflen; 24 if (_rdrand64_step(&val) != 1) { 25 error_print(); 26 return -1; 27 } 28 memcpy(buf, p, len); 29 buf += len; 30 buflen -= len; 31 } 32 return 1; 33 } 34 rdseed_bytes(uint8_t * buf,size_t buflen)35int rdseed_bytes(uint8_t *buf, size_t buflen) 36 { 37 uint64_t val; 38 uint8_t *p = (uint8_t *)&val; 39 40 while (buflen) { 41 size_t len = buflen >= sizeof(val) ? sizeof(val) : buflen; 42 if (_rdseed64_step(&val) != 1) { 43 error_print(); 44 return -1; 45 } 46 memcpy(buf, p, len); 47 buf += len; 48 buflen -= len; 49 } 50 return 1; 51 } 52