#!/usr/bin/perl -w

use Crypt::OpenSSL::Random;
use Crypt::OpenSSL::RSA;

  Crypt::OpenSSL::RSA->import_random_seed();

  if(-f "vendor-sec.pem")
  {
    print "Loading existing vendor key (delete the *.pem files, if you want to generate a new vendor key) ...\n";
    open IN,"<vendor-sec.pem";
    undef $/;
    my $sec_string=<IN>;
    close IN;
    $rsa = Crypt::OpenSSL::RSA->new_private_key($sec_string);

    open IN,"<vendor-pub.pem";
    undef $/;
    my $pub_string=<IN>;
    close IN;
    $rsa_pub = Crypt::OpenSSL::RSA->new_public_key($pub_string);


  if(open(IN,"<gen-priv.pem"))
  {
    undef $/;
    my $genpriv=<IN>;
    close IN;

    $genrsa = Crypt::OpenSSL::RSA->new_private_key($genpriv);

    $plaintext=`openssl rsa -pubout -in gen-priv.pem`;


    print "Signing the public key \n\n$plaintext\n\n";

    $signature = $rsa->sign($plaintext);

    #print "Signature: $signature\n";


    open OUT,">signatur.bin";
    print OUT $signature;
    close OUT;

    my $text="qcsr_default = ";
    foreach(unpack("C*",$signature))
    { 
      $text.=sprintf("%02X",$_);
    }

    print "hex: $text\n";


    open IN,"<openssl.cnf.vorlage";
    open OUT,">openssl.cnf";
    print OUT <IN>;
    print OUT $text."\n";
    close OUT;
    close IN;

    print "Signed correctly\n" if ($rsa_pub->verify($plaintext, $signature));
  }
  else
  {
    print "Private key not found (gen-priv.pem)!\n";
  }

  }
  else
  {
    print "Vendor key not found!\n";
  }

