使用C测试X509证书到期日期

Lal*_*mar 2 c openssl cryptography

如果X509?*证书过期,我该如何编程测试?他们是直接加密api?或者我必须得到not_after时间并在我的代码中手动检查它?

Tim*_*tje 5

你没有说出哪种语言,所以我总结了它们:

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']);
Run Code Online (Sandbox Code Playgroud)

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();
 }
Run Code Online (Sandbox Code Playgroud)

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 );
}
Run Code Online (Sandbox Code Playgroud)

C

X509 *x
time_t *ptime;
i=X509_cmp_time(X509_get_notBefore(x), ptime);
i=X509_cmp_time(X509_get_notAfter(x), ptime);
Run Code Online (Sandbox Code Playgroud)

  • 此外,该代码片段依赖于 .NET 类。提起它也没什么坏处。 (2认同)