ASN1_TIME 到 time_t 的转换 [英] ASN1_TIME to time_t conversion
问题描述
如何将 ASN1_TIME
转换为 time_t
格式?我想将 X509_get_notAfter()
的返回值转换为秒.
How can I convert ASN1_TIME
to time_t
format? I wanted to convert the return value of X509_get_notAfter()
to seconds.
推荐答案
时间在内部存储为字符串,格式为 YYmmddHHMMSS
或 YYYYmmddHHMMSS
.
Times are stored as a string internally, on the format YYmmddHHMMSS
or YYYYmmddHHMMSS
.
在字符串的末尾有几分之一秒和时区的空间,但现在让我们忽略它,并有一些(未经测试的)代码.
At the end of the string there is room for fractions of seconds and timezone, but let's ignore that for now, and have some (untested) code.
注意:另请参阅下面 Bryan Olson 的回答,其中讨论了由于 i++
导致的未定义行为.另请参阅 Seak 的答案,它消除了未定义的行为.
Note: also see Bryan Olson's answer below, which discusses the undefined behavior due to the i++
's. Also see Seak's answer which removes the undefined behavior.
static time_t ASN1_GetTimeT(ASN1_TIME* time)
{
struct tm t;
const char* str = (const char*) time->data;
size_t i = 0;
memset(&t, 0, sizeof(t));
if (time->type == V_ASN1_UTCTIME) /* two digit year */
{
t.tm_year = (str[i++] - '0') * 10 + (str[++i] - '0');
if (t.tm_year < 70)
t.tm_year += 100;
}
else if (time->type == V_ASN1_GENERALIZEDTIME) /* four digit year */
{
t.tm_year = (str[i++] - '0') * 1000 + (str[++i] - '0') * 100 + (str[++i] - '0') * 10 + (str[++i] - '0');
t.tm_year -= 1900;
}
t.tm_mon = ((str[i++] - '0') * 10 + (str[++i] - '0')) - 1; // -1 since January is 0 not 1.
t.tm_mday = (str[i++] - '0') * 10 + (str[++i] - '0');
t.tm_hour = (str[i++] - '0') * 10 + (str[++i] - '0');
t.tm_min = (str[i++] - '0') * 10 + (str[++i] - '0');
t.tm_sec = (str[i++] - '0') * 10 + (str[++i] - '0');
/* Note: we did not adjust the time based on time zone information */
return mktime(&t);
}
这篇关于ASN1_TIME 到 time_t 的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!