I am learning python and trying to convert the above code snippet found online to python.
As my understanding, the below code is generating the session key based upon SHA1 hash of the password "Microsoft" but I am not sure how I can derive AES 256 key based upon the hash of the password in python. And when I use AES.new()
, what IV
should be in this case? 16 Random bytes?
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 ) );
}