我如何在本机代码中从XML或模量/指数导入RSA公钥,以与Windows Capi的Cryptverifysignature一起使用?

StackOverflow https://stackoverflow.com/questions/3972655

在C#中,我能够以以下两种方式验证一个针对公共密钥的哈希:

// Import from raw modulus and exponent
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) {
    RSAParameters rsaKeyInfo = new RSAParameters {Modulus = modulus, Exponent = exponent};
    rsa.ImportParameters(rsaKeyInfo);
    return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA512"), signature);
}

// Import from XML
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) {
    rsa.FromXmlString(xmlPublicKey);
    return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA512"), signature);
}

我需要知道的是,考虑到Inbound RSA公钥,如何使用CAPI来完成同一件事?

除了了解如何将公共密钥导入加密提供商的上下文外,我具有验证哈希的大多数CAPI功能:

HCRYPTPROV hCryptProv;
HCRYPTHASH hHash;

CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0);
CryptCreateHash(hCryptProv, CALG_SHA512, 0, 0, &hHash);
CryptHashData(hHash, pDataToHash, lenDataToHash, 0);
CryptVerifySignature(hHash, pSignature, sigLength, NULL, CRYPT_NOHASHOID);
CryptDestroyHash(hHash);
CryptReleaseContext(hCryptProv, 0);

谢谢!

有帮助吗?

解决方案

利用 CryptImportKeyPUBLICKEYBLOB:

HCRYPTKEY hPublicKey;
DWORD keyBlobLength = sizeof(BLOBHEADER)+sizeof(RSAPUBKEY)+modulusLengthInBytes;
BYTE* keyBlob = malloc(keyBlobLength);
BLOBHEADER* blobheader = (BLOBHEADER*) keyBlob;
blobheader.bType    = PUBLICKEYBLOB;
blobheader.bVersion = CUR_BLOB_VERSION;
blobheader.reserved = 0;
blobheader.aiKeyAlg = CALG_RSA_KEYX;
RSAPUBKEY* rsapubkey = (RSAPUBKEY*) (keyBlob + sizeof(BLOBHEADER));
rsapubkey.magic     = 0x31415352;
rsapubkey.bitlen    = modulusLengthInBytes*8;
rsapubkey.pubexp    = 65537;         // Or whatever your public exponent is.
BYTE* modulus = keyBlob + sizeof(BLOBHEADER) + sizeof(RSAPUBKEY);
memcpy(modulus, ..., modulusLengthInBytes); // NOTE: modulus must be in LSB form,
                                     //       which is the opposite of what you
                                     //        usually have. 
                                     //       .NET will give you the modulus in
                                     //       MSB form, so you will have to
                                     //       reverse the order of the bytes.
CryptImportKey(hCryptProv, keyBlob, keyBlobLength, 0, 0, &hPublicKey);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top