+SimpleOpensslSigner::~SimpleOpensslSigner() {
+}
+
+std::shared_ptr<BIGNUM> SimpleOpensslSigner::nextSerial( uint16_t profile ) {
+ std::string res = readFile( "serial" );
+
+ BIGNUM* bn = 0;
+
+ if( res == "" ) {
+ bn = BN_new();
+
+ if( !bn ) {
+ throw "Initing serial failed";
+ }
+ } else {
+ if( !BN_hex2bn( &bn, res.c_str() + 1 ) ) {
+ throw "Parsing serial failed.";
+ }
+ }
+
+ std::shared_ptr<BIGNUM> serial = std::shared_ptr<BIGNUM>( bn, BN_free );
+
+ std::shared_ptr<unsigned char> data = std::shared_ptr<unsigned char>( ( unsigned char* ) malloc( BN_num_bytes( serial.get() ) + 20 ), free );
+ int len = BN_bn2bin( serial.get(), data.get() );
+
+ data.get()[len] = 0x0;
+ data.get()[len + 1] = 0x0; // signer id
+
+ data.get()[len + 2] = profile >> 8;
+ data.get()[len + 3] = profile & 0xFF; // profile id
+
+ if( !RAND_bytes( data.get() + len + 4, 16 ) || !BN_add_word( serial.get(), 1 ) ) {
+ throw "Big number math failed while calcing serials.";
+ }
+
+ std::shared_ptr<char> serStr = std::shared_ptr<char>(
+ BN_bn2hex( serial.get() ),
+ []( char* ref ) {
+ OPENSSL_free( ref );
+ } );
+ writeFile( "serial", serStr.get() );
+
+ return std::shared_ptr<BIGNUM>( BN_bin2bn( data.get(), len + 4 + 16 , 0 ), BN_free );
+}