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

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

PKCloud

Version 1.1.0 released

EzSign

Version 3.1.0 released

 

Our Mission

To create secure, highly available, easy to use products that are priced fairly

Please publish modules in offcanvas position.