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屋!