c++ - Crypto API RSA 公钥可以解密数据,不是预期的不对称

标签 c++ encryption rsa public-key cryptoapi

我遇到的问题是,我能够使用用于加密数据的相同 RSA 2048 位公钥来解密数据。在我看来,如果公钥可以解密数据,这首先会破坏加密数据的全部目的。此时我唯一可以考虑的是,当我认为我正在生成非对称对时,我正在生成对称 key 交换对。

最终用户这样做的目的是,当我无法从域中的工作站使用他们缓存的凭据时,稍后使用它来传输用户凭据以在办公室外使用应用程序时进行身份验证。理论上,我可以私钥来解密这些凭据。

我制作了一个简单的测试类和代码来重现我的问题。我正在采取的步骤如下:

  1. 获取 Microsoft Enhanced Cryptographic Provider v1.0 的上下文
  2. 生成公钥/私钥对。
  3. 将公钥和私钥 BLOB 导出到单独的文件。
  4. 加载公钥并加密一些简单的文本。
  5. 尝试使用公钥解密相同的加密文本(我预计它会在这里失败,除非我使用私钥 - 但两者都有效)。

TestEncryptDecrypt 辅助类:TestEncryptDecrypt.h

#pragma once
#include <Windows.h>
#include <wincrypt.h>

class TestEncryptDecrypt
{
public:
    TestEncryptDecrypt()
    {
    }
    ~TestEncryptDecrypt()
    {
        if (hKey != NULL)
            CryptDestroyKey(hKey);

        if (hProvider != NULL)
            CryptReleaseContext(hProvider, 0);
    }

    BOOL InitializeProvider(LPCTSTR pszProvider, DWORD dwProvType)
    {
        if (hProvider != NULL)
        {
            if (!CryptReleaseContext(hProvider, 0))
                return 0;
        }

        return CryptAcquireContext(&hProvider, NULL, pszProvider, dwProvType, 0);
    }

    BOOL Generate2048BitKeys(ALG_ID Algid)
    {
        DWORD dwFlags = (0x800 << 16) | CRYPT_EXPORTABLE;
        return CryptGenKey(hProvider, Algid, dwFlags, &hKey);
    }

    VOID ExportPrivatePublicKey(LPTSTR lpFileName)
    {
        if (hKey == NULL)
            return;

        DWORD dwDataLen = 0;
        BOOL exportResult = CryptExportKey(hKey, NULL, PRIVATEKEYBLOB, 0, NULL, &dwDataLen);
        LPBYTE lpKeyBlob = (LPBYTE)malloc(dwDataLen);
        exportResult = CryptExportKey(hKey, NULL, PRIVATEKEYBLOB, 0, lpKeyBlob, &dwDataLen);
        WriteBytesFile(lpFileName, lpKeyBlob, dwDataLen);
        free(lpKeyBlob);
    }

    VOID ExportPublicKey(LPTSTR lpFileName)
    {
        if (hKey == NULL)
            return;

        DWORD dwDataLen = 0;
        BOOL exportResult = CryptExportKey(hKey, NULL, PUBLICKEYBLOB, 0, NULL, &dwDataLen);
        LPBYTE lpKeyBlob = (LPBYTE)malloc(dwDataLen);
        exportResult = CryptExportKey(hKey, NULL, PUBLICKEYBLOB, 0, lpKeyBlob, &dwDataLen);
        WriteBytesFile(lpFileName, lpKeyBlob, dwDataLen);
        free(lpKeyBlob);
    }

    BOOL ImportKey(LPTSTR lpFileName)
    {
        if (hProvider == NULL)
            return 0;

        if (hKey != NULL)
            CryptDestroyKey(hKey);

        LPBYTE lpKeyContent = NULL;
        DWORD dwDataLen = 0;
        ReadBytesFile(lpFileName, &lpKeyContent, &dwDataLen);
        BOOL importResult = CryptImportKey(hProvider, lpKeyContent, dwDataLen, 0, 0, &hKey);

        delete[] lpKeyContent;

        return importResult;
    }

    BOOL EncryptDataWriteToFile(LPTSTR lpSimpleDataToEncrypt, LPTSTR lpFileName)
    {
        DWORD SimpleDataToEncryptLength = _tcslen(lpSimpleDataToEncrypt)*sizeof(TCHAR);
        DWORD BufferLength = SimpleDataToEncryptLength * 10;
        BYTE *EncryptedBuffer = new BYTE[BufferLength];
        SecureZeroMemory(EncryptedBuffer, BufferLength);
        CopyMemory(EncryptedBuffer, lpSimpleDataToEncrypt, SimpleDataToEncryptLength);

        BOOL cryptResult = CryptEncrypt(hKey, NULL, TRUE, 0, EncryptedBuffer, &SimpleDataToEncryptLength, BufferLength);
        DWORD dwGetLastError = GetLastError();

        WriteBytesFile(lpFileName, EncryptedBuffer, SimpleDataToEncryptLength);

        delete[] EncryptedBuffer;

        return cryptResult;
    }

    BOOL DecryptDataFromFile(LPBYTE *lpDecryptedData, LPTSTR lpFileName, DWORD *dwDecryptedLen)
    {
        if (hKey == NULL)
            return 0;

        LPBYTE lpEncryptedData = NULL;
        DWORD dwDataLen = 0;
        ReadBytesFile(lpFileName, &lpEncryptedData, &dwDataLen);
        BOOL decryptResult = CryptDecrypt(hKey, NULL, TRUE, 0, lpEncryptedData, &dwDataLen);
        *dwDecryptedLen = dwDataLen;
        //WriteBytesFile(L"decryptedtest.txt", lpEncryptedData, dwDataLen);
        *lpDecryptedData = new BYTE[dwDataLen + 1];
        SecureZeroMemory(*lpDecryptedData, dwDataLen + 1);
        CopyMemory(*lpDecryptedData, lpEncryptedData, dwDataLen);

        delete[]lpEncryptedData;

        return decryptResult;
    }

    VOID WriteBytesFile(LPTSTR lpFileName, BYTE *content, DWORD dwDataLen)
    {
        HANDLE hFile = CreateFile(lpFileName, GENERIC_READ | GENERIC_WRITE, 0x7, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        DWORD dwBytesWritten = 0;
        WriteFile(hFile, content, dwDataLen, &dwBytesWritten, NULL);
        CloseHandle(hFile);
    }

private:
    HCRYPTPROV hProvider = NULL;
    HCRYPTKEY hKey = NULL;

    VOID ReadBytesFile(LPTSTR lpFileName, BYTE **content, DWORD *dwDataLen)
    {
        HANDLE hFile = CreateFile(lpFileName, GENERIC_READ, 0x7, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
        DWORD dwFileLength = 0;
        DWORD dwBytesToRead = GetFileSize(hFile, NULL);
        DWORD dwBytesRead = 0;

        *content = new BYTE[dwBytesToRead + 1];
        SecureZeroMemory(*content, dwBytesToRead + 1);

        ReadFile(hFile, *content, dwBytesToRead, &dwBytesRead, NULL);

        *dwDataLen = dwBytesRead;

        CloseHandle(hFile);
    }
};

测试代码: main.cpp 文件

#include "stdafx.h"
#include "TestEncryptDecrypt.h"
#include <Windows.h>
#include <wincrypt.h>

int main()
{
    TestEncryptDecrypt *edc = new TestEncryptDecrypt();
    //Initialize the provider
    edc->InitializeProvider(MS_ENHANCED_PROV, PROV_RSA_FULL);

    //Generate a 2048-bit asymmetric key pair
    edc->Generate2048BitKeys(CALG_RSA_KEYX);

    //Export the private / public key pair
    edc->ExportPrivatePublicKey(L"privpubkey.txt");

    //Export only the public key
    edc->ExportPublicKey(L"pubkey.txt");

    //Import the public key (destroys the private/public key pair already set)
    edc->ImportKey(L"pubkey.txt");

    //Encrypt and write some test data to file
    edc->EncryptDataWriteToFile(TEXT("Hello World!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), L"encrypteddata.txt");

    //Decrypt the data from file using the same public key (this should fail but it doesn't)
    DWORD dwDataLen = 0;
    LPBYTE lpDecryptedData = NULL;
    edc->DecryptDataFromFile(&lpDecryptedData, L"encrypteddata.txt", &dwDataLen);

    //Write the supposedly decrypted data to another file
    edc->WriteBytesFile(L"decrypteddata.txt", lpDecryptedData, dwDataLen);

    //Clear data
    delete[] lpDecryptedData;
    delete edc;

    return 0;
}

不幸的是,我没有机会经常使用 C++,因此您可能会注意到一些问题。随时提出建设性的批评。

有谁知道为什么我可以使用相同的公钥解密数据? 我的目标是能够在客户端不可逆地加密某些内容,而这些内容只能在服务器上解密,私钥将隐藏在服务器上。

编辑: 我认为 hKey 没有被 ImportKey 方法正确销毁,所以我写了这个测试用例(相同的结果 - 公钥可以加密和解密数据):

// CPPTests.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "TestEncryptDecrypt.h"
#include <Windows.h>
#include <wincrypt.h>

int main()
{
    TestEncryptDecrypt *edc = new TestEncryptDecrypt();
    //Initialize the provider
    edc->InitializeProvider(MS_ENHANCED_PROV, PROV_RSA_FULL);

    //Generate a 2048-bit asymmetric key pair
    edc->Generate2048BitKeys(CALG_RSA_KEYX);

    //Export the private / public key pair
    edc->ExportPrivatePublicKey(L"privpubkey.txt");

    //Export only the public key
    edc->ExportPublicKey(L"pubkey.txt");

    //Destroy everything and load up only the public key to write some encrypted data
    delete edc;
    edc = new TestEncryptDecrypt();
    edc->InitializeProvider(MS_ENHANCED_PROV, PROV_RSA_FULL);
    edc->ImportKey(L"pubkey.txt");

    //Encrypt and write some test data to file
    edc->EncryptDataWriteToFile(TEXT("Hello World!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"), L"encrypteddata.txt");

    //Destroy everything and load up only the public key to read some encrypted data
    delete edc;
    edc = new TestEncryptDecrypt();
    edc->InitializeProvider(MS_ENHANCED_PROV, PROV_RSA_FULL);
    edc->ImportKey(L"pubkey.txt");

    //Decrypt the data from file using the same public key (this should fail but it doesn't)
    DWORD dwDataLen = 0;
    LPBYTE lpDecryptedData = NULL;
    edc->DecryptDataFromFile(&lpDecryptedData, L"encrypteddata.txt", &dwDataLen);

    //Write the supposedly decrypted data to another file
    edc->WriteBytesFile(L"decrypteddata.txt", lpDecryptedData, dwDataLen);

    //Clear data
    delete[] lpDecryptedData;
    delete edc;

    return 0;
}

最佳答案

此 API 已弃用 according to Microsoft ,所以如果您是来这里寻找原生加密 API,您可能想看看其他地方。

在与同样的问题进行了一番斗争之后,我意识到了错误所在。

在您的第一个代码中,您获取上下文时最后一个标志设置为零:

CryptAcquireContext(&hProvider, NULL, pszProvider, dwProvType, 0);

但在您的解决方案中,您将其更改为 CRYPT_VERIFYCONTEXT。

CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);

您通过更改此标志解决了您的问题,而不是通过从 OpenSSL 导入 key 。我很确定,如果您在初始代码中对此进行测试,它将按预期工作。

此 CRYPT_VERIFYCONTEXT 标志负责不允许 key 在系统中实现持久性,这种持久性使公共(public) RSA 能够加密和解密。

关于c++ - Crypto API RSA 公钥可以解密数据,不是预期的不对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324466/

相关文章:

c++ - 除了内容(例如类型、位置)之外,变量是否还消耗内存?

iphone - 我有 : RSA key, 指数,明文。我想要 : cipher text. 应该是 2 行 Obj-C 不是吗?

c++ - 在 msgpack 的 C++ 实现中,如何在使用 pack_map 或 pack_array 序列化对象后反序列化对象?

c++ - 为什么以下代码片段会加速代码?

c# - 验证 TLS 电子邮件接收

mysql - 在 mysql : Unknown system variable 'block_encryption_mode' 中更改 aes 的 aes 模式时出错

java - AES加密/解密: Given final block not properly padded

perl - Perl 中的 RSA key

cryptography - RSA key 长度和导出限制

c++ - 如何将 vector 列表中的对象复制到另一个 vector 列表?