Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASN1_TIME_print functionality without BIO?

Tags:

c

openssl

As described in this question: Openssl C++ get expiry date, there is the possibility to write an ASN1 time into a BIO buffer and then read it back into a custom buffer buf:

BIO *bio;
int write = 0;
bio = BIO_new(BIO_s_mem());
if (bio) {
  if (ASN1_TIME_print(bio, tm))
    write = BIO_read(bio, buf, len-1);
  BIO_free(bio);
}
buf[write]='\0';
return write;

How could this be achieved without using BIO at all? The ASN1_TIME_print function is only present when OPENSSL_NO_BIO is not defined. Is there a way to write the time directly into a given buffer?

like image 567
eckes Avatar asked Sep 07 '25 05:09

eckes


1 Answers

You can try the sample code below. It doesn't use BIO, but should give you the same output as the OP's example. If you don't trust the ASN1_TIME string, you'll want to add some error checking for:

  • notBefore->data is > 10 chars
  • each char value is between '0' and '9'
  • values for year, month, day, hour, minute, second
  • type

You should test for the type (i.e. UTC), if you expect multiple types.

You should also test whether or not the date/time is GMT and add that to the string if you want the output to match exactly as if using BIOs. see: openssl/crypto/asn1/t_x509.c - ASN1_UTCTIME_print or ASN1_GENERALIZEDTIME_print


ASN1_TIME* notBefore = NULL;
int len = 32;
char buf[len];
struct tm tm_time;

notBefore = X509_get_notBefore(x509_cert);

// Format ASN1_TIME  with type UTC into a tm struct
if(notBefore->type == V_ASN1_UTCTIME){
    strptime((const char*)notBefore->data, "%y%m%d%H%M%SZ" , &tm_time);
    strftime(buf, sizeof(char) * len, "%h %d %H:%M:%S %Y", &tm_time);
}

// Format ASN1_TIME with type "Generalized" into a tm struct
if(notBefore->type == V_ASN1_GENERALIZEDTIME){
     // I didn't look this format up, but it shouldn't be too difficult
}
like image 174
Steve Miskovetz Avatar answered Sep 10 '25 10:09

Steve Miskovetz