您可以尝试下面的示例代码。它不使用 BIO,但应该为您提供与 OP 示例相同的输出。如果您不信任 ASN1_TIME 字符串,则需要添加一些错误检查:
- notBefore->数据> 10个字符
- 每个 char 值在 '0' 和 '9' 之间
- 年、月、日、时、分、秒的值
- 类型
如果您期望多种类型,您应该测试类型(即 UTC)。
您还应该测试日期/时间是否为 GMT,如果您希望输出与使用 BIO 完全匹配,请将其添加到字符串中。请参阅:openssl/crypto/asn1/t_x509.c - ASN1_UTCTIME_print 或 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
}