CryptoAPI:如何使用CryptVerifySignature验证来自OpenSSL或Java的DSA签名

时间:2011-02-17 19:51:53

标签: openssl digital-signature cryptoapi

我希望能够使用Microsoft CryptoAPI验证OpenSSL生成的DSA签名。

请考虑您有以下输入:

  • 现有的DSA公钥:
  • 要验证的数据
  • 二进制签名

签名已从Base64转换为48个字节的系列。

2 个答案:

答案 0 :(得分:5)

如果不了解CryptoAPI,这应该是非常困难的。

主要障碍是:

  • 使用CryptStringToBinaryA和CryptDecodeObjectEx解码X509 DSA公钥
  • 转换DSA签名格式
    • OpenSSL的DSA_sign以ASN.1 DER格式生成DSA签名
    • CryptoAPI的CryptVerifySignature需要P1363格式的DSA签名

以下是我最终如何解决问题的粗略示例:

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而失败。