Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# GetExpirationDateString() returning data in short date format creating issue

I have to check and ensure a certificate is not expired using the below code:

if (DateTime.Parse(cert.GetExpirationDateString()) <= DateTime.Now)
{
     _logger.Log(LogLevel.Error, "Chain Certificate is Expired");
     return false;
} 

cert is a instance of X509Certificate class of .net.

Issue that am facing is GetExpirationDateString function gives the date of expiry in string format(which depends upon the short date format of the current culture)

If the short date format of my machine is DD-MM-YY it returns expiry date 21-12-2030 as 21-12-30, DateTime.Parse function converts 30 to 1930 (if the expiry year is >30).

Is there a way by which I can get the certificate expiry always in dd/mm/yyyy format in order to avoid this issue?

like image 779
saurabh vats Avatar asked Jul 26 '16 13:07

saurabh vats


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

Why is C named so?

Because a and b and c , so it's name is C. C came out of Ken Thompson's Unix project at AT&T. He originally wrote Unix in assembly language. He wrote a language in assembly called B that ran on Unix, and was a subset of an existing language called BCPL.


1 Answers

The string representation year 30 will always be converted by default to 1930 and never to 2030 when parsing a DateTime no matter how you try it. Your best bet is to do as @Glorin suggested and use X509Certificate2. This type has a constructor that takes an instance of X509Certificate. Alternatively you can generate using one of the other constructors. Here is a code sample based on what you provided:

var cert2 = new X509Certificate2(cert);
if(cert2.NotAfter <= DateTime.Now)
{
     _logger.Log(LogLevel.Error, "Chain Certificate is Expired");
     return false;
} 
like image 121
Igor Avatar answered Oct 23 '22 09:10

Igor