首页 > 解决方案 > 如何在 Windows 上将 bcrypt_gensalt 与 /dev/urandom 一起使用?

问题描述

我使用这个 BCrypt 库生成一个带盐的哈希:https ://github.com/rg3/libbcrypt

问题在bcrypt.c( int bcrypt_gensalt) 中。open("/dev/urandom", O_RDONLY)在 Windows 上不起作用。我尝试了以下方法:

int bcrypt_gensalt(int factor, char salt[BCRYPT_HASHSIZE]) {
    int fd;
    unsigned char input[RANDBYTES];
    int workf;
    char *aux;

    HCRYPTPROV hCryptProv;

    if (CryptAcquireContext(
        &hCryptProv,
        NULL,
        (LPCSTR)"Microsoft Base Cryptographic Provider v1.0",
        PROV_RSA_FULL,
        CRYPT_VERIFYCONTEXT)) {
        if (CryptGenRandom(
            hCryptProv,
            RANDBYTES,
            input)) {

            if (CryptReleaseContext(hCryptProv, 0)) {
                return 0;
            }
            else {
                printf("Error during CryptReleaseContext.\n");
            return 4;
            }
        }
        else {
            if (CryptReleaseContext(hCryptProv, 0)) {
                printf("Error during CryptGenRandom.\n");
                return 2;
            }
            else {
                printf("Error during CryptReleaseContext.\n");
                return 3;
            }
        }
    }
    else {
        printf("Error during CryptAcquireContext!\n");
        return 1;
    }

    /* Generate salt. */
    workf = (factor < 4 || factor > 31)?12:factor;
    aux = crypt_gensalt_rn("$2a$", workf, input, RANDBYTES,
                   salt, BCRYPT_HASHSIZE);
    return (aux == NULL)?5:0;
}

但结果是:

Generated salt:
Hashed password: *0
Time taken: 0.000000 seconds
First hash check: OK
Second hash check: OK
First hash check with bcrypt_checkpw: OK
Time taken: 0.060000 seconds
Second hash check with bcrypt_checkpw: OK
Time taken: 0.060000 seconds

盐不会正确生成。

标签: c++windowsvisual-studiocng

解决方案


在您致电:

aux = crypt_gensalt_rn("$2a$", workf, input, RANDBYTES,
                   salt, BCRYPT_HASHSIZE);

RANDBYTES的和的值BCRYPT_HASHSIZE需要多一个字节才能终止\0

您是否尝试过(使用RANDBYTES-1and BCRYPT_HASHSIZE-1)?


推荐阅读