Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing X509 Certificate Expiry date with C

How can I programaticlaly test if a X509 ?* certificate is expired or not ? Is their a direct crypto api ? or I have to get the not_after time and check it manually in my code ?

like image 943
Lalita Kumar Avatar asked Dec 25 '22 09:12

Lalita Kumar


2 Answers

You didn't say which language so I was summing them up anyway:

php

$data = openssl_x509_parse(file_get_contents('/path/to/cert.crt'));

$validFrom = date('Y-m-d H:i:s', $data['validFrom_time_t']);
$validTo = date('Y-m-d H:i:s', $data['validTo_time_t']);

Java X509Certificate

InputStream inStream = null;

 try (InputStream inStream = new FileInputStream("fileName-of-cert")) {
     CertificateFactory cf = CertificateFactory.getInstance("X.509");
     X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);

     // check if valid on specific date (now set for today)
     cert.checkValidity(new Date());
     // Date nBefore = cert.getNotBefore();
     // Date nAfter = cert.getNotAfter();
 }

C++

using namespace System;
using namespace System::Security::Cryptography::X509Certificates;
int main()
{

   // The path to the certificate.
   String^ Certificate = "Certificate.cer";

   // Load the certificate into an X509Certificate object.
   X509Certificate^ cert = X509Certificate::CreateFromCertFile( Certificate );

   // Get the value.
   String^ results = cert->GetExpirationDateString();

   // Display the value to the console.
   Console::WriteLine( results );
}

C

X509 *x
time_t *ptime;
i=X509_cmp_time(X509_get_notBefore(x), ptime);
i=X509_cmp_time(X509_get_notAfter(x), ptime);
like image 120
Timmetje Avatar answered Jan 06 '23 02:01

Timmetje


You should be able to use:

result=X509_cmp_time(X509_get_notBefore(cert), ptime);

and

result=X509_cmp_time(X509_get_notAfter(cert), ptime);

using OpenSSL. I'm not sure if you can get it less "manual" than that.

like image 37
Maarten Bodewes Avatar answered Jan 06 '23 02:01

Maarten Bodewes