CryptDecrypt在解密字符串的末尾返回随机字符

CryptDecrypt returns random characters at the end of decrxpted string?

本文关键字:返回 随机 字符 解密 字符串 CryptDecrypt      更新时间:2023-10-16

我正在尝试制作一个简单的应用程序,它对字符串进行加密,然后解密。到目前为止,我的代码:

int main( int argc, char* argv[] )
{  
char test[ 32 ] = { 0 };  
strcpy( test, "This is a sample string." );  
BYTE buf = NULL;  
DWORD len = strlen( test );  
EncryptData( lpszPassword, test, &len );
return 0; 
}
void EncryptData( TCHAR *lpszPassword, char *pbBuffer, DWORD *dwCount )
{
HCRYPTPROV hProv = 0;
HCRYPTKEY hKey = 0;
HCRYPTHASH hHash = 0;
LPWSTR wszPassword = lpszPassword;
DWORD cbPassword = ( wcslen( wszPassword ) + 1 )*sizeof( WCHAR );
if ( !CryptAcquireContext( &hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT ) )
{
    printf( "Error %x during CryptAcquireContext!n", GetLastError() );
    goto Cleanup;
}
if ( !CryptCreateHash( hProv, CALG_SHA_256, 0, 0, &hHash ) )
{
    printf( "Error %x during CryptCreateHash!n", GetLastError() );
    goto Cleanup;
}
if ( !CryptHashData( hHash, ( PBYTE )wszPassword, cbPassword, 0 ) )
{
    printf( "Error %x during CryptHashData!n", GetLastError() );
    goto Cleanup;
}
if ( !CryptDeriveKey( hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey ) )//hKey
{
    printf( "Error %x during CryptDeriveKey!n", GetLastError() );
    goto Cleanup;
}
DWORD size = ( DWORD )strlen( pbBuffer ) / sizeof( char );
printf( "nLength of string = %d", size );
if ( !CryptEncrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size, BLOCK_SIZE ) )
{
    printf( "Error %x during CryptEncrypt!n", GetLastError() );
    goto Cleanup;
}
printf( "nEncrypted bytes  = %d", size );
printf( "nEncrypted text = %s", pbBuffer );
if ( !CryptDecrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size ) )
{
    printf( "Error %x during CryptDecrypt!n", GetLastError() );
    goto Cleanup;
}
printf( "nDecrypted bytes  = %d", size );
printf( "nDecrypted text = %s", pbBuffer );
Cleanup:
if ( hKey )
{
    CryptDestroyKey( hKey );
}
if ( hHash )
{
    CryptDestroyHash( hHash );
}
if ( hProv )
{
    CryptReleaseContext( hProv, 0 );
}
}

这会产生输出:

Length of string = 24
Encrypted bytes  = 32
Encrypted text = ╨é╖·ç┤╠├ó br.≡·►;╜K/┤E(↓)╫%┤Cà¡╩╠╠╠╠╘)Ñ°♀·L
Decrypted bytes  = 24
Decrypted text = This is a sample string.)╫%┤Cà¡╩╠╠╠╠╘)Ñ°♀·L

基本上,它几乎可以工作,但在加密字符串的和处,加密字符串中还有字符。

所以我的问题是,我是做错了什么,还是只是错过了什么?

提前感谢!

给定"%s"时,printf函数需要一个以NULL结尾的字符串。显然,字符串不是以NULL结尾的(实际上,NULL是谁知道在哪里找到的,但printf()在打印数据的有效部分很久之后才找到它)。

使用您为解密的文本检索到的size值。这是有效的实际字节数。

这里的解决方案不仅纠正了size和解密数据的问题,而且还纠正了使用goto的问题。

#include <string>
#include <iostream>
using namespace std;
struct CryptStuff
{
     HCRYPTPROV* hProv;
     HCRYPTKEY* hKey;
     HCRYPTHASH* hHash;
     CryptStuff(HCRYPTPROV* hprov, HCRYPTKEY* hkey, HCRYPTHASH* hash) :
                   hProv(hprov), hKey(hkey), hHash(hash) {}
      ~CryptStuff() 
       { 
         if ( *hKey ) CryptDestroyKey( *hKey );
         if ( *hHash ) CryptDestroyHash( *hHash );
         if ( *hProv ) CryptReleaseContext( *hProv, 0 );
       }
};
void EncryptData( TCHAR *lpszPassword, char *pbBuffer, DWORD *dwCount )
{
    HCRYPTPROV hProv = 0;
    HCRYPTKEY hKey = 0;
    HCRYPTHASH hHash = 0;
    // create an instance of CryptStuff.  This will cleanup the data on return
    CryptStuff cs(&hProv, &hKey, &hHash);
    LPWSTR wszPassword = lpszPassword;
    DWORD cbPassword = ( wcslen( wszPassword ) + 1 )*sizeof( WCHAR );
    if ( !CryptAcquireContext( &hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 
                               CRYPT_VERIFYCONTEXT ) )
    {
        return;
    }
    if ( !CryptCreateHash( hProv, CALG_SHA_256, 0, 0, &hHash ) )
    {
        return;
    }
    if ( !CryptHashData( hHash, ( PBYTE )wszPassword, cbPassword, 0 ) )
    {
        return;
    }
    if ( !CryptDeriveKey( hProv, CALG_AES_256, hHash, CRYPT_EXPORTABLE, &hKey ) )
    {
        return;
    }
    DWORD size = ( DWORD )strlen( pbBuffer ) / sizeof( char );
    cout << "nLength of string = " << size;
    if ( !CryptEncrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size, BLOCK_SIZE ) )
    {
        return;
    }
    cout << "nEncrypted bytes  = " << size;
    cout << "nEncrypted text = ";
    cout.write(pbBuffer, size);
    if ( !CryptDecrypt( hKey, 0, TRUE, 0, ( LPBYTE )pbBuffer, &size ) )
    {
        return;
    }
    cout << "nDecrypted bytes  = " << size;
    cout << "nDecrypted text = ";
    cout.write(pbBuffer, size);
}

我写这篇文章时没有编译器,所以请原谅任何拼写错误。为了简洁起见,我还删除了错误输出。

上面的代码首先通过使用cout.write来输出适当数量的字符(由size值表示)来校正解密数据的问题。这保证了我们可以得到我们想要的字符输出。我使用了cout.write,因为未加密的数据包含嵌入的NULL是完全可以接受的,而且我们不想在字符串中出现的第一个NULL时停止。我们希望在达到输出的size字符数后停止。


接下来要做的是使用一种名为RAII(资源获取即初始化)的技术来删除goto。注意这是如何做到的:

我们首先创建了一个名为CryptStuff的结构,它包含指向我们要清理的3个项目的指针。在这个结构中,我们有一个析构函数来清理这些项。为了利用这个结构,我们在EncryptData内部创建了一个名为cs的实例,并为构造中的实例提供了3个项的地址。

因此,基本上,当EncryptData返回时,cs实例将自动调用其析构函数,这意味着我们将清理句柄。这比使用goto(实际上任何东西都比goto更好)或棘手的冗余编码来清理句柄要有利得多。原因是清理是自动的——无论返回EncryptData的原因是什么,即return或某个函数导致抛出异常,我们都可以清理句柄。

此外,如果以后代码变得更加复杂,则无需记住为每个新的返回场景反复"添加goto"或"编写清理代码"。注意,错误条件执行简单的return而不需要goto

RAII信息可以在这里找到:

资源获取是初始化(RAII)是什么意思?

在编写C++代码时,它是一个重要的部分,必须管理创建的和必须一致销毁的资源。