CertificateStore.cs

Contains the code for accessing certificates stored in the windows certificate store, by using the certificate thumbprint.

// ------------------------------------------------------------------------------------------
// <copyright file="CertificateStore.cs" company="Pointsharp AB">
//   Pointsharp AB
// </copyright>
// <summary>
//   Defines the CertificateStore class.
// </summary>
// -------------------------------------------------------------------------------------------

namespace SecMaker.NiP.Client
{
	using System.Text;
	using System.Security.Cryptography.X509Certificates;

	/// <summary>
	/// Defines the CertificateStore class.
	/// </summary>
	internal class CertificateStore
	{
		/// <summary>
		/// Get certificate including handler from personal certificate store.
		/// </summary>
		/// <param name="crtHash">
		/// The hash (thumbprint) of the client certificate as System.String.
		/// </param>
		/// <returns>
		/// Returns the certificate as System.Security.Cryptography.X509Certificates.X509Certificate2.
		/// </returns>
		internal static X509Certificate2 GetCertificate(string crtHash)
		{
			if (string.IsNullOrEmpty(crtHash))
			{
				return null;
			}

			var certHash =
				new StringBuilder(crtHash.ToUpper().Trim());

			const string approvedChars =
				"0123456789ABCDEF";

			for (var i = 0; i < certHash.Length; i++)
			{
				var thisChar =
					certHash[i];

				if (approvedChars.IndexOf(thisChar) > -1)
				{
					continue;
				}

				certHash.Remove(i, 1);

				i--;
			}

			var x509Store =
				new X509Store(StoreName.My, StoreLocation.CurrentUser);

			x509Store.Open(OpenFlags.MaxAllowed);

			foreach (var certificate in x509Store.Certificates)
			{
				if (certificate.GetCertHashString() == certHash.ToString())
				{
					return certificate;
				}
			}

			return null;
		}
	}
}