If you wish to extract the signer certificate from a PKCS#7/CMS formatted signature using C#, the following steps can be used:
Add a Reference
From your .NET project, add a reference to System.Security
Directives
Add the following using directives to your source file:
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
Code
The following method will accept a base64 encoded signature and return the signer certificate
You will then be able to extract details from this certificate as required
public X509Certificate getSignerCert(String b64Signature)
{
byte[] binarySignature = Convert.FromBase64String(b64Signature);
SignedCms cms = new SignedCms();
cms.Decode(binarySignature);
SignerInfoCollection coll = cms.SignerInfos;
// Normally there is just the one signer certificate, which this will return
SignerInfoEnumerator siEnum = coll.GetEnumerator();
if (siEnum.MoveNext())
{
X509Certificate signerCert = siEnum.Current.Certificate;
return signerCert;
}
// If you are expecting more than one signer, then use the following
// to extract the signer from each signature
/*
foreach (SignerInfo si in coll)
{
X509Certificate cert = si.Certificate;
// Add cert to array and return the array
}
*/
throw new Exception("No signer certificate was found in the provided signature");
}
Example
String b64Signature = "MIAGCSqGSIb3D....MocqJA56a3n3vJUk=";
X509Certificate signerCert = getSignerCert(b64Signature);
String serialNum = signerCert.GetSerialNumberString();
String subject = signerCert.Subject;