C# - Obtain Signer Certificate from Signature

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;

 

 

 

 

Contact Us

Email: This email address is being protected from spambots. You need JavaScript enabled to view it.

Call: 020 8938 3616

Krestfield Limited, 124 City Road, London, EC1V 2NX

Sales & Support

Should you need any help with any of Krestfield's products, or wish to make any suggestions, please contact us.

Sales: sales@krestfield.com

Support: support@krestfield.com

Latest News

certdog

Version 1.9.0 released

PKCloud

Version 4.1.2 released

 

Our Mission

To create secure, highly available, intuitive products that are affordably priced

Please publish modules in offcanvas position.