📄 x509sn.h
字号:
#ifndef __X509_SERIAL_H
#define __X509_SERIAL_H
class X509_sn
{
public:
static BIGNUM * Load_Serial ( const char * serialfile, bool create, ASN1_INTEGER ** retai );
static int Save_Serial ( const char * serialfile, const char * suffix, BIGNUM * bn, ASN1_INTEGER ** retai );
};
//从序列文件中读取序列号
inline
BIGNUM * X509_sn::Load_Serial ( const char * serialfile,
bool create,
ASN1_INTEGER ** retai )
{
BIGNUM * bnret = 0;
BIO * bin = 0;
ASN1_INTEGER * ai = 0;
char buf[BUFSIZZ] = {0};
if ( serialfile == 0 ) goto end;
if ( ( ai = ASN1_INTEGER_new () ) == NULL ) goto end;
if ( ( bin = BIO_new ( BIO_s_file () ) ) == NULL ) goto end;
if ( BIO_read_filename ( bin, serialfile ) <= 0 )
{
if ( create )
{
//新建
ASN1_INTEGER_set ( ai, 1 );
bnret = BN_new ( );
if ( bnret )
BN_one ( bnret );
}
}
else
{
//读取
if ( !a2i_ASN1_INTEGER ( bin, ai, buf, BUFSIZZ ) )
{
CError::Interface()->Handle_Error ( 0, "读取序列号失败:%s", serialfile );
goto end;
}
//转换
if ( ( bnret = ASN1_INTEGER_to_BN ( ai, NULL) ) == NULL )
{
CError::Interface()->Handle_Error ( 0, "数据转换失败(BIN->BIGNUM)" );
goto end;
}
}
if ( bnret && retai )
{
*retai = ai;
ai = NULL;
}
end:
if ( bin ) BIO_free ( bin );
if ( ai ) ASN1_INTEGER_free ( ai );
return bnret;
}
//保存序列号到序列号文件
inline
int X509_sn::Save_Serial ( const char * serialfile,
const char * suffix,
BIGNUM * bnsn, ASN1_INTEGER ** retai )
{
BIO * bout = 0;
ASN1_INTEGER * ai = 0;
char buf[BUFSIZZ] = {0};
int ret = -1, filelen;
if ( serialfile == 0 ) return ret;
//判断文件长度
filelen = strlen ( serialfile );
if ( suffix )
filelen += strlen ( suffix );
if ( filelen > BUFSIZZ )
{
CError::Interface()->Handle_Error ( 0, "序列号文件过长:%s", serialfile );
goto end;
}
//增加后缀
BUF_strlcpy ( buf, serialfile, BUFSIZZ );
if ( suffix )
BIO_snprintf ( buf, sizeof buf, "%s.%s", serialfile, suffix );
//生成IO
if ( ! ( bout = BIO_new ( BIO_s_file () ) ) == NULL ) goto end;
if ( BIO_write_filename ( bout, buf ) <= 0 )
{
CError::Interface()->Handle_Error ( 0, "写文件失败:%s", buf );
goto end;
}
if ( (ai = BN_to_ASN1_INTEGER ( bnsn, NULL ) ) == NULL )
{
CError::Interface()->Handle_Error ( 0, "转换格式失败(序列号->ASN.1)" );
goto end;
}
i2a_ASN1_INTEGER ( bout, ai );
if ( retai )
{
*retai = ai;
ai = 0;
}
ret = 0;
end:
if ( bout ) BIO_free ( bout );
if ( ai ) ASN1_INTEGER_free ( ai );
return ret;
}
#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -