c – 加密API RSA公钥可以解密数据,不像预期的那样不对称

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

最终用户的目的是稍后使用它来传输用户凭证,以便在远离办公室使用应用程序时进行身份验证,此时我无法使用域中工作站的缓存凭据.理论上,我只能使用私钥解密这些凭据.

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

>获取Microsoft Enhanced Cryptographic Provider v1.0的上下文
>生成公钥/私钥对.
>将公钥和私钥BLOB导出为单独的文件.
>加载公钥并加密一些简单的文本.
>尝试使用公钥解密相同的加密文本(我希望它在这里失败,除非我使用私钥时 – 但两者都有效).

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);
    }
};

测试代码:主.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;
}

最佳答案 经过一些与同样问题的斗争,我意识到错误在哪里.

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

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

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

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

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

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

点赞