sgx_status_t sgx_read_rand(unsigned char *rand, size_t length_in_bytes) { // check parameters // // rand can be within or outside the enclave if(!rand || !length_in_bytes) { return SGX_ERROR_INVALID_PARAMETER; } if(!sgx_is_within_enclave(rand, length_in_bytes) && !sgx_is_outside_enclave(rand, length_in_bytes)) { return SGX_ERROR_INVALID_PARAMETER; } // loop to rdrand uint32_t rand_num = 0; while(length_in_bytes > 0) { sgx_status_t status = __do_get_rand32(&rand_num); if(status != SGX_SUCCESS) { return status; } size_t size = (length_in_bytes < sizeof(rand_num)) ? length_in_bytes : sizeof(rand_num); memcpy(rand, &rand_num, size); rand += size; length_in_bytes -= size; } memset_s(&rand_num, sizeof(rand_num), 0, sizeof(rand_num)); return SGX_SUCCESS; }
/* The function should generate a random number properly, and the pseudo-rand implementation is only for demo purpose. */ sample_status_t sample_read_rand(unsigned char *rand, size_t length_in_bytes) { // check parameters if(!rand || !length_in_bytes) { return SAMPLE_ERROR_INVALID_PARAMETER; } // loop to rdrand while(length_in_bytes > 0) { uint32_t rand_num = 0; sample_status_t status = __do_get_rand32(&rand_num); if(status != SAMPLE_SUCCESS) { return status; } size_t size = (length_in_bytes < sizeof(rand_num)) ? length_in_bytes : sizeof(rand_num); if(memcpy_s(rand, size, &rand_num, size)) { return status; } rand += size; length_in_bytes -= size; } return SAMPLE_SUCCESS; }