File: bcrypt.d

package info (click to toggle)
ldc 1%3A1.41.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 64,576 kB
  • sloc: cpp: 91,105; ansic: 23,829; makefile: 1,518; sh: 1,056; asm: 724; objc: 135; exp: 50; python: 12
file content (65 lines) | stat: -rw-r--r-- 1,520 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
module std.internal.windows.bcrypt;

version (Windows):

import core.sys.windows.bcrypt : BCryptGenRandom, BCRYPT_USE_SYSTEM_PREFERRED_RNG;
import core.sys.windows.windef : HMODULE, PUCHAR, ULONG;
import core.sys.windows.ntdef : NT_SUCCESS;

pragma(lib, "Bcrypt.lib");

package(std) bool bcryptGenRandom(T)(out T result) @trusted
{
    loadBcrypt();

    const gotRandom = ptrBCryptGenRandom(
        null,
        cast(PUCHAR) &result,
        ULONG(T.sizeof),
        BCRYPT_USE_SYSTEM_PREFERRED_RNG,
    );

    return NT_SUCCESS(gotRandom);
}

private
{
    HMODULE hBcrypt = null;
    typeof(BCryptGenRandom)* ptrBCryptGenRandom;
}

private void loadBcrypt() @nogc nothrow
{
    import core.sys.windows.winbase : GetProcAddress, LoadLibraryA;

    if (!hBcrypt)
    {
        hBcrypt = LoadLibraryA("Bcrypt.dll");
        if (!hBcrypt)
            assert(false, `LoadLibraryA("Bcrypt.dll") failed.`); // `@nogc`

        ptrBCryptGenRandom = cast(typeof(ptrBCryptGenRandom)) GetProcAddress(hBcrypt , "BCryptGenRandom");
        if (!ptrBCryptGenRandom)
            assert(false, `GetProcAddress(hBcrypt , "BCryptGenRandom") failed.`); // `@nogc`
    }
}

// Will free `Bcrypt.dll`.
private void freeBcrypt() @nogc nothrow
{
    import core.sys.windows.winbase : FreeLibrary;

    if (hBcrypt)
    {
        if (!FreeLibrary(hBcrypt))
            assert(false, `FreeLibrary("Bcrypt.dll") failed.`); // `@nogc`

        hBcrypt = null;
        ptrBCryptGenRandom = null;
    }
}

static ~this()
{
    freeBcrypt();
}