簡體   English   中英

C ++使用CNG從模數和指數中導入RSA公鑰

[英]C++ Importing RSA public keys from modulus and exponent with CNG

我正在嘗試使用CNG通過作為參數給出的公共密鑰來加密某些數據。 調用NCryptImportKey函數時,出現NTE_BAD_DATA錯誤,該錯誤未在msdn頁面中列出。

我的代碼:

#include <iostream>
#include <Windows.h>
#include <Bcrypt.h>
#include <Ntstatus.h>
#include <string>
#include <vector>
#include "base64.h"

using std::string;
using std::vector;

struct MyRSAPublicBlob {
    BCRYPT_RSAKEY_BLOB blob;
    BYTE exponent[3];
    BYTE modulus[128];
    MyRSAPublicBlob(const vector<BYTE>& mod, const vector<BYTE>& exp)
    {
        blob.BitLength = (128 + 3) * 8;
        blob.Magic = BCRYPT_RSAPUBLIC_MAGIC;
        blob.cbModulus = 128;
        blob.cbPublicExp = 3;
        for (size_t i = 0; i < mod.size(); ++i) //copy BigEndian
            modulus[i] = mod[mod.size() - 1 - i];
        for (size_t i = 0; i < exp.size(); ++i) //copy BigEndian
            exponent[i] = exp[exp.size() - 1 - i];
    }
    MyRSAPublicBlob() { ; }

};

MyRSAPublicBlob b;

bool RSA_encrypt() {
    SECURITY_STATUS stat;
    NCRYPT_PROV_HANDLE hProv;
    NCRYPT_KEY_HANDLE hKey;

    stat = NCryptOpenStorageProvider(&hProv, MS_KEY_STORAGE_PROVIDER, 0);
    if (ERROR_SUCCESS != stat) {
        std::cout << "failed in NCryptOpenStorageProvider: " << GetLastError() << std::endl;
        return false;
    }
    stat = NCryptImportKey(hProv,
        NULL,
        BCRYPT_RSAPUBLIC_BLOB,
        NULL,
        &hKey,
        (PBYTE)&b.blob,
        sizeof(b),
        0);

    if (ERROR_SUCCESS != stat) {
        std::cout << "failed in NCryptImportKey: " << GetLastError() << std::endl;
        return false;
    }

我如何構造MyRSAPublicBlob的示例:

string PubKeyModulus = "yVUndgQFuB5Z5FgC0/WgWCg6Y8VuB582avGjQDdeoJDa1+RBKCyXo700sAMSGjM/bVakOlFqvCsVFNBysx1CH731CDb2DR1a0bsmYmDQ9d0ZHX+AOohVDIx9mc7bkDQZoEFpe9NqFsu95Y9yktpl1JKPmKyLOFgufGJYYvQyoOM=";
string PubKeyExp = "AQAB";

vector<BYTE> PubKeyModulus_bin = base64_decode(PubKeyModulus);
vector<BYTE> PubKeyExp_bin = base64_decode(PubKeyExp);
struct MyRSAPublicBlob c(PubKeyModulus_bin, PubKeyExp_bin);
b = c;

我直率做錯了什么嗎?

BitLength值是“密鑰的大小”,對於RSA來說,是“模數值的大小”。 因此,對於cbModulus來說有點多余,但是c'est la vie。

如果您在計算BitLength時刪除了+ 3 ,它將可能開始工作。 與.NET相比,為RSACng.ImportParameters構建Blob: http : //source.dot.net/#System.Security.Cryptography.Cng/Common/System/Security/Cryptography/RSACng.ImportExport.cs,79

RSA公鑰BLOB(BCRYPT_RSAPUBLIC_BLOB)在連續內存中具有以下格式。 嘗試使用#pragma pack以避免任何填充問題。 例如,

#pragma pack(push, 1)
struct MyRSAPublicBlob {
    BCRYPT_RSAKEY_BLOB blob;
    BYTE exponent[3];
    BYTE modulus[32];
...};
#pragma pack(pop)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM