c++ - CryptDecrypt 在解密字符串的末尾返回随机字符?

标签 c++ windows cryptography

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

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 和解密数据问题,还可以纠正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 或某些函数导致抛出异常,我们开始清理 handle 。

此外,如果稍后代码变得更复杂,则无需记住为每个新的返回场景一遍又一遍地“添加一个 goto”或“编写清理代码”。请注意,错误条件会执行简单的return,而无需 goto

可以在这里找到 RAII 信息:

What is meant by Resource Acquisition is Initialization (RAII)?

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

关于c++ - CryptDecrypt 在解密字符串的末尾返回随机字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26660049/

相关文章:

windows - 更改 Windows 上可执行命令的顺序

windows - MFC CheckBox - 检索准确的正方形大小

c++ - 使用 CryptVerifySignature 的数字签名

c# - 使用 protobuf 将类型 System.Drawing.Rectangle 从 .Net 序列化为 C++

c++ - 使用 Boost::graph 随机访问顶点

c++ - 0xc000007b 错误和 Microsoft Visual C++ 2010 x86 运行时

security - 为什么多次调用 X509Certificate2.Export(Pkcs12) 返回不同的结果?

c++ - 显式默认的移动构造函数

c++ - 运算符重载错误 "no match for operator error"

vba - 从 VBA 调用 .NET 加密