| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
#include <aws/common/device_random.h> |
| 6 |
|
| 7 |
#include <aws/common/byte_buf.h> |
| 8 |
|
| 9 |
#include <windows.h> |
| 10 |
|
| 11 |
#include <bcrypt.h> |
| 12 |
|
| 13 |
int aws_device_random_buffer(struct aws_byte_buf *output) { |
| 14 |
return aws_device_random_buffer_append(output, output->capacity - output->len); |
| 15 |
} |
| 16 |
|
| 17 |
int aws_device_random_buffer_append(struct aws_byte_buf *output, size_t n) { |
| 18 |
AWS_PRECONDITION(aws_byte_buf_is_valid(output)); |
| 19 |
|
| 20 |
size_t space_available = output->capacity - output->len; |
| 21 |
if (space_available < n) { |
| 22 |
AWS_POSTCONDITION(aws_byte_buf_is_valid(output)); |
| 23 |
return aws_raise_error(AWS_ERROR_SHORT_BUFFER); |
| 24 |
} |
| 25 |
|
| 26 |
size_t original_len = output->len; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
while (n > 0) { |
| 31 |
uint32_t capped_n = (uint32_t)aws_min_size(n, UINT32_MAX); |
| 32 |
|
| 33 |
NTSTATUS status = |
| 34 |
BCryptGenRandom(NULL, output->buffer + output->len, capped_n, BCRYPT_USE_SYSTEM_PREFERRED_RNG); |
| 35 |
|
| 36 |
if (!BCRYPT_SUCCESS(status)) { |
| 37 |
output->len = original_len; |
| 38 |
AWS_POSTCONDITION(aws_byte_buf_is_valid(output)); |
| 39 |
return aws_raise_error(AWS_ERROR_RANDOM_GEN_FAILED); |
| 40 |
} |
| 41 |
|
| 42 |
output->len += capped_n; |
| 43 |
n -= capped_n; |
| 44 |
} |
| 45 |
|
| 46 |
AWS_POSTCONDITION(aws_byte_buf_is_valid(output)); |
| 47 |
return AWS_OP_SUCCESS; |
| 48 |
} |