How to AES CBC encryption Using cryptoAPI

爱⌒轻易说出口 提交于 2020-01-03 06:06:37

问题


I want to encrypt a file with AES CBC mode encryption, Using cryptoAPI functions and set my own key from the command-line (It my change in the code)

I imagine that the key (after change) will be 1a1dc91c907325c6 and tried in this form:

HCRYPTPROV hProv  = NULL;
HCRYPTKEY hKey    = NULL;
DWORD dwBlobLen;
PBYTE pbKeyBlob = NULL;
pbKeyBlob = (PBYTE)"1a1dc91c907325c6";

if(!CryptAcquireContext(&hProv, NULL,NULL, PROV_RSA_AES,CRYPT_VERIFYCONTEXT))
{
    printf(" Error in AcquireContext 0x%08x \n",GetLastError());
}    
if (!CryptImportKey(hProv,pbKeyBlob,sizeof(pbKeyBlob),0,CRYPT_EXPORTABLE,&hKey ))
{
    printf("Error 0x%08x in importing the Des key \n",GetLastError());
}

but CryptImportKey failed

I don't know how to use cryptoAPI functions and It's parameters

I tested some other codes and change the parameters or function's call's order for about 2 weeks but I wasn't able to do this

Please help me [a big help :)]

Thank you


回答1:


You should do it like this:

if( ::CryptAcquireContext( &m_hCryptoProvider, NULL, NULL/*Default*/, PROV_RSA_AES, CRYPT_VERIFYCONTEXT ) )
{
    //Hash Password
    // CALG_SHA1 OK
    // CALG_AES_128 / CALG_AES_256 => error
    if( ::CryptCreateHash( m_hCryptoProvider, CALG_SHA1, 0, 0, &m_hHashPassword ) )
    {
        // Hash for the password. 
        if( ::CryptHashData( m_hHashPassword, (BYTE *)password, (DWORD) _tcslen(password) * sizeof(TCHAR), 0 ) )
        {
            // Session key from the hash
            if( ::CryptDeriveKey( m_hCryptoProvider, CALG_AES_256, m_hHashPassword, CRYPT_CREATE_SALT, &m_hCryptKey ) )
            {
                TRACE( TEXT("Crypto-API OK\n") ); 
                return ERROR_SUCCESS;
            }
            else
            {
                TRACE( TEXT("Error in CryptDeriveKey\n") ); 
            }
        }
        else
        {
            TRACE( TEXT("Error in CryptHashData\n") ); 
        }
    }
    else
    { 
        TRACE( TEXT("Error in CryptCreateHash\n") );
    }
}
else
{
    TRACE( TEXT("Error in CryptAcquireContext\n") );
}

After that you need to use CryptEncrypt/CryptDecrypt to do encode/decode data.



来源:https://stackoverflow.com/questions/29636767/how-to-aes-cbc-encryption-using-cryptoapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!