2

I have generated a pair of private/public keys and I have managed to load the private key to sign some bytes. The problem ocurrs when I try to load the public key from memory to verify the signature.

Here is some code :

  privateKey := BIO_new(BIO_s_mem);
  PEM_write_bio_RSAPrivateKey(privateKey,rsa,enc,nil,0,nil,PChar('1234567890'));
  publicKey := BIO_new(BIO_s_mem);
  PEM_write_bio_RSAPublicKey(publicKey,rsa);
  WriteLn(GetErrorMessage);
  //No error so far
  Writeln('Keys generated!');
  pKey := nil;
  PEM_read_bio_PrivateKey(privateKey,pKey,nil,PChar('1234567890'));
  // pKey is ok
  mKey := nil;
  PEM_read_bio_PUBKEY(publicKey,mKey,nil,nil);
  WriteLn(GetErrorMessage); 

The error message output by the last line is

PEM routines : PEM_read_bio : no start line

What am I doing wrong ?

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
opc0de
  • 11,557
  • 14
  • 94
  • 187
  • I'd suggest looking on how Indy is doing it... –  Dec 29 '12 at 09:00
  • 1
    if u can't use OpenSSL, then perhaps using other libraries ? LovkBox3, Spring4Delphi, etc ? – Arioch 'The Dec 29 '12 at 10:21
  • openssl is pretty fast and I would like to understand what am I doing wrong rather then switching to something else – opc0de Dec 29 '12 at 10:25
  • @TobyAllen : PEM routines : PEM_read_bio : no start line – opc0de Dec 30 '12 at 10:43
  • Two things to look at for debugging: Is `mKey` being populated with anything at all? Also, what do you get if you just try to read everything from `publicKey` (using `BIO_read()` or similar); i.e. does what is being written to memory _look_ like a valid PEM-encoded object? – atomicinf Jan 01 '13 at 08:08
  • @atomicinf : mKey = nil if i Use BIO_read() the output is a PEM-encoded object – opc0de Jan 03 '13 at 07:34

1 Answers1

4

The problem is that you're mixing PEM_write_bio_RSAPublicKey() and PEM_read_bio_PUBKEY(). The former writes a PKCS#1 RSAPublicKey structure, while the latter expects a SubjectPublicKeyInfo structure. The two structures are not interchangeable, hence your error upon read.

To resolve this error, use PEM_write_bio_RSA_PUBKEY() when writing your public key to BIO.

atomicinf
  • 3,596
  • 19
  • 17
  • I will try your suggestion and come back with an answer later this day.Thanks! – opc0de Jan 03 '13 at 09:52
  • PEM_write_bio_RSA_PUBKEY is not defined in the unit I use.Could you supply a definition for it ? Thanks – opc0de Jan 03 '13 at 16:34
  • @opc0de From http://stackoverflow.com/questions/9723963/delphi-pascal-example-for-calling-openssl-evp-functions: `function PEM_write_bio_RSA_PUBKEY(bp: PBIO; x: PRSA): integer; cdecl;` I don't actually do Delphi, but I work with OpenSSL on an almost daily basis. Had the wrong function here originally; just woke up >_> – atomicinf Jan 03 '13 at 16:43