Install Certificate From File - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:Certificate

Description

Install Certificate From File

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using System.Security.Cryptography.X509Certificates;
using System.IO;//from w w  w.ja  va2  s  . c  o  m
using System.Collections.Concurrent;

public class Main{
        public static X509Certificate2 InstallCertificateFromFile(string pfxFile, string passwordFile, StoreLocation storeLocation)
        {
            var certPassword = File.ReadAllText(passwordFile);
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromFile(pfxFile, certPassword);
            CertificateHelper.InstallCertificate(certificate, storeLocation);

            return certificate;
        }
        public static X509Certificate2 InstallCertificateFromFile(string pfxFile, string passwordFile)
        {
            return InstallCertificateFromFile(pfxFile, passwordFile, StoreLocation.LocalMachine);
        }
        public static void InstallCertificate(X509Certificate2 certificate, StoreLocation storeLocation)
        {
            var store = new X509Store(StoreName.My, storeLocation);

            try
            {
                store.Open(OpenFlags.ReadWrite);
                store.Add(certificate);
            }
            finally
            {
                store.Close();
            }
        }
        public static X509Certificate2 GetCertificateFromFile(string fileName, string password)
        {
            X509Certificate2 certificate;
            if (certificatesFromFiles.TryGetValue(fileName, out certificate))
            {
                return certificate;
            }

            certificate = new X509Certificate2(fileName, password, X509KeyStorageFlags.Exportable);
            certificatesFromFiles[fileName] = certificate;
            return certificate;
        }
}

Related Tutorials