Skip to content

Instantly share code, notes, and snippets.

@madmonkey
Created April 7, 2013 17:22
Show Gist options
  • Save madmonkey/5331419 to your computer and use it in GitHub Desktop.
Save madmonkey/5331419 to your computer and use it in GitHub Desktop.
Extension methods for X509 Certificates
namespace BitWise.Utilities.Certificate
{
using System;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
//using log4net;
/// <summary>
/// Extension methods for X509 certificates
/// </summary>
static class CertificateHelper
{
/// <summary>
/// Formatted thumbprint.
/// </summary>
/// <param name="x509">The X509Certificate.</param>
/// <returns></returns>
public static string FormattedThumbprint(this X509Certificate x509)
{
return string.Join(" ", x509.GetCertHash().Select(h => h.ToString("x2")));
}
/// <summary>
/// Gets the UTC value from string.
/// </summary>
/// <param name="x509">The X509Certificate.</param>
/// <param name="dateTimeValue">The date time value.</param>
/// <returns></returns>
public static DateTime GetUtcFromString(this X509Certificate x509, string dateTimeValue)
{
return x509.GetLocalFromString(dateTimeValue).ToUniversalTime();
}
/// <summary>
/// Gets the local from string.
/// </summary>
/// <param name="x509">The self.</param>
/// <param name="dateTimeValue">The date time value.</param>
/// <returns></returns>
public static DateTime GetLocalFromString(this X509Certificate x509, string dateTimeValue)
{
return DateTime.Parse(dateTimeValue);
}
/// <summary>
/// Validates the effectiveness.
/// </summary>
/// <param name="x509">The X509Certificate.</param>
/// <param name="cert">The cert.</param>
/// <param name="logger">The logger.</param>
public static void ValidateEffectiveness(this X509Certificate x509, string cert, ILog logger)
{
try
{
var expires = x509.GetUtcFromString(x509.GetExpirationDateString());
if ((expires - DateTime.UtcNow).TotalDays < 30)
{
//logger.WarnFormat("The {0} certificate [{1}] is set to expire in less than 30 days on {2}", cert, x509.Subject, expires.ToString("o", CultureInfo.InvariantCulture));
}
if ((expires - DateTime.UtcNow).TotalDays <= 0)
{
//logger.ErrorFormat("The {0} certificate [{1}] has expired on {2}", cert, x509.Subject, expires.ToString("o", CultureInfo.InvariantCulture));
}
}
catch (Exception exception)
{
//logger.Error("Unable to make determination of certificate's 'freshness'", exception);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment