v2 / vlib / crypto / rand / rand_windows.c.v
23 lines · 19 sloc · 734 bytes · 008aaad99981918c51194d7aaaaaccb4c258f244
Raw
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
5module rand
6
7#flag windows -Llibraries/bcrypt
8#flag windows -lbcrypt
9#include <bcrypt.h>
10
11const status_success = 0x00000000
12const bcrypt_use_system_preferred_rng = 0x00000002
13
14// read returns an array of `bytes_needed` random bytes read from the OS.
15pub 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