Mentalis.org Security Library documentation

Certificate Services

Loading .pfx/.p12 files

The following example demonstrates how a typical program would load certificate file that's stored in the Private Information Exchange format. These types of certificates are usually stored in files with a .pfx or .p12 extension. To load other types of certificate files, take a look at this example code.

using System;
using System.IO;
using Org.Mentalis.Security.Certificates;

/// <summary>
/// Loads a certificate from a certificate file.
/// </summary>
/// <param name="filename">The file that contains the certificate.</param>
/// <param name="password">The password used to encrypt the private key.</param>
/// <returns>A Certificate instance.</returns>
/// <exception cref="ArgumentNullException">filename or password is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="FileNotFoundException">filename could not be found on the
/// hard disk.</exception>
/// <exception cref="CertificateException">An error occurs while opening the
/// certificate store.</exception>
public Certificate LoadPfxFile(string filename, string password) {
    if (filename == null || password == null)
        throw new ArgumentNullException(filename == null ? "filename" : "password",
            "Invalid argument.");
    if (!File.Exists(filename))
        throw new FileNotFoundException("Couldn't find the certificate file.");
    // open the file and convert it to a CertificateStore instance
    CertificateStore store = CertificateStore.CreateFromPfxFile(filename, password);
    // find the first certificate in the store
    // if no certificate is found, this method return 'null'
    Certificate cert = store.FindCertificate();
    if (cert == null)
        throw new CertificateException("The specified store is empty.");
    return cert;
}