Get the size of public key using WinHttpQueryOption

449 Views Asked by At

I need to find the Public key specified in certificate details. I have used WinHttpQuery option and provided WINHTTP_OPTION_SERVER_CERT_CONTEXT as the option flag.

bRet = WinHttpQueryOption(
hRequest,
WINHTTP_OPTION_SERVER_CERT_CONTEXT,
&pCert,
&dwLen

);

I found the public key encryption type using the structure returned from WinhttpQueryOption. Now I need to find the size of the public key

Example : RSA(2048 bits)

Is there a way to find the size of the public key using this method or is there any other way?

Sample of certificate details

1

There are 1 best solutions below

0
Keshav On

After hours of searching, I finally came up with the solution.

With WinHttpQueryOption, use WINHTTP_OPTION_SERVER_CERT_CONTEXT as the option flag and get the structure pCert(CERT_CONTEXT) . Now get the PCERT_INFO member of the structure to get details about the certificate. In PCERT_INFO use the SubjectPublicKeyInfo member, use the the function CertGetPublicKeyLength() and pass the SubjectPublicKeyInfo member as an argument to it. That function returns the length of the public key.

Code :

bRet = WinHttpQueryOption(
hRequest,
WINHTTP_OPTION_SERVER_CERT_CONTEXT,
&pCert,
&dwLen
);

cout<<"Alg Name : "<<pCert->pCertInfo-
>SubjectPublicKeyInfo.Algorithm.pszObjId<<endl;
CRYPT_BIT_BLOB pubKey = pCert->pCertInfo->SubjectPublicKeyInfo.PublicKey;

DWORD pLength = CertGetPublicKeyLength(X509_ASN_ENCODING | 
PKCS_7_ASN_ENCODING,&pCert->pCertInfo->SubjectPublicKeyInfo);
cout<<"Length of public key : "<<pLength<<endl;