| 1 | // Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT license |
| 3 | // that can be found in the LICENSE file. |
| 4 | |
| 5 | module rand |
| 6 | |
| 7 | #flag windows -Llibraries/bcrypt |
| 8 | #flag windows -lbcrypt |
| 9 | #include <bcrypt.h> |
| 10 | |
| 11 | const status_success = 0x00000000 |
| 12 | const bcrypt_use_system_preferred_rng = 0x00000002 |
| 13 | |
| 14 | // read returns an array of `bytes_needed` random bytes read from the OS. |
| 15 | pub fn read(bytes_needed int) ![]u8 { |
| 16 | mut buffer := []u8{len: bytes_needed} |
| 17 | // use bcrypt_use_system_preferred_rng because we passed null as algo |
| 18 | status := C.BCryptGenRandom(0, buffer.data, bytes_needed, bcrypt_use_system_preferred_rng) |
| 19 | if status != status_success { |
| 20 | return &ReadError{} |
| 21 | } |
| 22 | return buffer |
| 23 | } |
| 24 | |