如何在没有.NET / COM的情况下通过加密服务提供程序(CSP)生成随机字节?

时间:2012-11-05 16:35:53

标签: node.js

有没有办法通过Microsoft的加密服务提供程序(CSP)生成强大的随机字节而不使用.NET / COM?例如,使用命令行还是其他方式?

我想在NodeJS中使用它更具体。

2 个答案:

答案 0 :(得分:1)

请参阅http://technet.microsoft.com/en-us/library/cc733055(v=ws.10).aspx

netsh nap client set csp name = <name> keylength = <keylength>

如果此命令适用于您,只需通过nodejs执行即可。 (要求( 'child_process')。EXEC)

答案 1 :(得分:1)

是的,使用Windows API。这是一个示例C ++代码:

#include "Wincrypt.h"

// ==========================================================================
HCRYPTPROV hCryptProv= NULL; // handle for a cryptographic provider context

// ==========================================================================
void DoneCrypt()
{
    ::CryptReleaseContext(hCryptProv, 0);
    hCryptProv= NULL;
}

// --------------------------------------------------------------------------
// acquire crypto context and a key ccontainer
bool InitCrypt()
{
    if (hCryptProv) // already initialized
        return true;

    if (::CryptAcquireContext(&hCryptProv        ,   // handle to the CSP
                              NULL               ,   // container name
                              NULL               ,   // use the default provider
                              PROV_RSA_FULL      ,   // provider type
                              CRYPT_VERIFYCONTEXT )) // flag values
    {
        atexit(DoneCrypt);
        return true;
    }

    REPORT(REP_ERROR, _T("CryptAcquireContext failed"));
    return false;
}

// --------------------------------------------------------------------------
// fill buffer with random data
bool RandomBuf(BYTE* pBuf, size_t nLen)
{
    if (!hCryptProv)
        if (!InitCrypt())
            return false;

    size_t nIndex= 0;

    while (nLen-nIndex)
    {
        DWORD nCount= (nLen-nIndex > (DWORD)-1) ? (DWORD)-1 : (DWORD)(nLen-nIndex);
        if (!::CryptGenRandom(hCryptProv, nCount, &pBuf[nIndex]))
        {
            REPORT(REP_ERROR, _T("CryptGenRandom failed"));
            return false;
        }

        nIndex+= nCount;
    }

    return true;
}