Reputation: 4242
I'd like to calculate the CERT_KEY_IDENTIFIER_PROP_ID
of a X509 certificate to add it silently to the registry of a Windows Mobile device (during staging). As of this site, it's calculated like this:
SEQ[SEQ[rsa], key]
I guess the key
is cert.GetPublicKey()
, but what's meant with rsa
here (not the algorithm I guess)?
Searching the web for three hours now, I would be very glad if someone could point me into the right direction.
Upvotes: 1
Views: 542
Reputation: 4242
To read the properties I need to write to the registry key, I finally used the following CryptoAPI methods:
[DllImport("crypt32.dll", SetLastError = true)]
private static extern IntPtr CertCreateCertificateContext(int dwCertEncodingType, byte[] pbCertEncoded, int cbCertEncoded);
[DllImport("crypt32.dll", SetLastError = true)]
private static extern bool CertFreeCertificateContext(IntPtr pCertContext);
[DllImport("crypt32.dll", SetLastError = true)]
private static extern bool CertGetCertificateContextProperty(IntPtr pCertContext, int dwPropId, IntPtr pvData, ref int pcbData);
private byte[] GetKeyIdentifier(X509Certificate certificate)
{
var data = certificate.GetRawCertData();
var context = CertCreateCertificateContext(1, data, data.Length);
try
{
return ReadProperty(context, 0x14);
}
finally
{
CertFreeCertificateContext(context);
}
}
private byte[] ReadProperty(IntPtr context, int property)
{
var length = 0;
// determine the ammount of memory to allocate for the data
if (CertGetCertificateContextProperty(context, property, IntPtr.Zero, ref length))
{
var pointer = Marshal.AllocCoTaskMem(length);
try
{
// query the property which is written to the allocated memory
if (CertGetCertificateContextProperty(context, property, pointer, ref length) == false)
{
throw new InvalidOperationException(string.Format("Failed to query property {0}.", property));
}
// extract the data from the unmanaged memory
var buffer = new byte[length];
Marshal.Copy(pointer, buffer, 0, length);
return buffer;
}
finally
{
Marshal.FreeCoTaskMem(pointer);
}
}
else
{
throw new InvalidOperationException(string.Format("Failed to query property {0}.", property));
}
}
Upvotes: 3