我希望能够使用Microsoft CryptoAPI验证OpenSSL生成的DSA签名。
请考虑您有以下输入:
签名已从Base64转换为48个字节的系列。
答案 0 :(得分:5)
如果不了解CryptoAPI,这应该是非常困难的。
主要障碍是:
以下是我最终如何解决问题的粗略示例:
const char* pubKey = "MIIBtjCCASsGByqGSM44BAEwggEeAoGBANW/k8nYREKtRMvIShnJTSAwxF33haU4"
.....
"/FEGAibbOp31rjq9UfaJ2t06eN0t0B+DP1hjz/MfpGtPOxHqF3dQnDRa3ot1FSTP";
bool verify(const unsigned char* msgData, unsigned int msgLength, const unsigned char* signature, unsigned int signatureLength)
{
HCRYPTPROV hCryptProv;
if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_DSS, CRYPT_VERIFYCONTEXT))
{
return false;
}
bool result = false;
unsigned char derPubKey[2048];
DWORD derPubKeyLen = 2048;
CERT_PUBLIC_KEY_INFO *publicKeyInfo = NULL;
DWORD publicKeyInfoLen = 0;
if ( CryptStringToBinaryA( pubKey, strlen(pubKey), CRYPT_STRING_BASE64, derPubKey, &derPubKeyLen, NULL, NULL ) &&
CryptDecodeObjectEx( X509_ASN_ENCODING, X509_PUBLIC_KEY_INFO, derPubKey, derPubKeyLen,
CRYPT_ENCODE_ALLOC_FLAG, NULL, &publicKeyInfo, &publicKeyInfoLen ) )
{
HCRYPTKEY hPubKey;
if (CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING, publicKeyInfo, &hPubKey))
{
HCRYPTHASH hHash;
if (CryptCreateHash(hCryptProv, CALG_SHA1, 0, 0, &hHash))
{
CryptHashData(hHash, msgData, msgLength, 0);
BYTE* dsaSignature = NULL;
DWORD dsaSignatureLen = 0;
if (CryptDecodeObjectEx( X509_ASN_ENCODING, X509_DSS_SIGNATURE, signature, signatureLength,
CRYPT_ENCODE_ALLOC_FLAG, NULL, &dsaSignature, &dsaSignatureLen ) )
{
if (CryptVerifySignature(hHash, dsaSignature, dsaSignatureLen, hPubKey, NULL, 0))
{
result = true;
}
LocalFree(dsaSignature);
}
CryptDestroyHash(hHash);
}
CryptDestroyKey(hPubKey);
}
LocalFree(publicKeyInfo);
}
CryptReleaseContext(hCryptProv, 0);
return result;
}
答案 1 :(得分:2)
请注意,Microsoft的加密API不支持大于1024的DSA密钥长度.CryptImportPublicKeyInfo()将因NTE_BAD_DATA而失败。