用pyCyp将C++中的AES加密代码转换为Python

2024-09-30 22:26:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python并尝试将上面的代码片段转换成python。在

据我所知,下面的代码是根据密码“Microsoft”的SHA1散列生成会话密钥的,但我不确定如何根据python中密码的哈希值来导出aes256密钥。{{cd1>在这种情况下应该使用什么?16个随机字节?在

string encrypt ( const char *s ) 
{
    DWORD dwSize = strlen ( s );
    DWORD dwSize2 = strlen ( s );
    HCRYPTHASH hHash = NULL;
    HCRYPTKEY hKey = NULL;
    HCRYPTPROV hProv = NULL;
    char *buffer;

    char *pwd = "Microsoft"; 
    int pwdLen = strlen ( pwd );

    // CryptAcquireContext function is used to acquire a handle to a particular key container within a particular cryptographic service provider (CSP)
    if ( ! CryptAcquireContext ( &hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0 ) )
    {
        printf ( "Unable to acquire encryption context\n" );
        return NULL;
    }

    // CryptCreateHash function initiates the hashing of a stream of data. It creates and returns to the calling application a handle to a cryptographic service provider (CSP) hash object
    if ( ! CryptCreateHash ( hProv, CALG_SHA1, 0, 0, &hHash ) )
    {
        CryptReleaseContext ( hProv, 0 );
        printf ( "Unable to create hash\n" );
        return NULL;
    }

    // CryptHashData function adds data to a specified hash object
    if ( ! CryptHashData ( hHash, (const byte *)pwd, pwdLen, 0 ) )
    {
        CryptDestroyHash ( hHash );
        CryptReleaseContext ( hProv, 0 );
        printf ( "Unable to add key\n" );
        return NULL;
    }

    // CryptDeriveKey function generates cryptographic session keys derived from a base data value
    if ( ! CryptDeriveKey ( hProv, CALG_AES_256, hHash, 0, &hKey ) )
    {
        CryptDestroyHash ( hHash );
        CryptReleaseContext ( hProv, 0 );
        printf ( "Unable to derive key\n" );
        return NULL;
    }

    // CryptEncrypt function encrypts data; have API return us the required buffer size
    CryptEncrypt ( hKey, 0, true, 0, 0, &dwSize, strlen ( s ) ); 

}

Tags: tokeydatareturnifpwdfunctionnull