2

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

据我了解,以下代码是根据密码“Microsoft”的 SHA1 哈希生成会话密钥,但我不确定如何根据 python 中密码的哈希导出 AES 256 密钥。当我使用时AES.new()IV在这种情况下应该是什么?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 ) ); 

}
4

0 回答 0