On Thu, Jan 15, 2004, Matt Margush wrote:

> Hi,
> 
> I searched the mailing list archives but couldn't find this question.  
> When I run the following code, I get an "EXC_BAD_ACCESS" signal at line 
>  29.  If I reverse the order (encode the private key first, then the 
> public key), then the error happens on the call to encode the public 
> key.  So it seems like encoding one key might do something to the DSA 
> structure that makes it impossible to encode the other key... or (more 
> likely), something is wrong with my code here (which I hope is the case 
> because it will be easier to fix.)  I am using version 0.9.7.
> 
> Thanks,
> 
> Matt
> 
> 
> #include <stdio.h>
> #include <openssl/dsa.h>
> 
> int main (int argc, const char * argv[]) {
>     DSA *dsa = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, NULL, 
> NULL);
>     DSA_generate_key(dsa);
> 
>     {
>         unsigned char *buffer;
>         unsigned char *p = buffer;
>         int length;
> 
>         length = i2d_DSAPublicKey(dsa, NULL);
>         if (length > -1) {
>             buffer = OPENSSL_malloc(length);
>             i2d_DSAPublicKey(dsa, &p);
>             OPENSSL_free(buffer);
>         }
>     }
> 
>     {
>         unsigned char *buffer;
>         unsigned char *p = buffer;
>         int length;
> 
>         length = i2d_DSAPrivateKey(dsa, NULL);
>         if (length > -1) {
>             buffer = OPENSSL_malloc(length);
>             i2d_DSAPrivateKey(dsa, &p);   /* THIS IS LINE 29 */
>             OPENSSL_free(buffer);
>         }
>     }
> 
>     DSA_free(dsa);
> 
>     return 0;
> }
> 

As someone has pointed out you need to set p to the buffer after you've set it
to a valid block of memory. 

For 0.9.7 or later you can simplify this to:

buffer = NULL;
length = i2d_DSAPrivateKey(dsa, &buffer);

which will allocate and encode in one operation and it will *not* increment
buffer so you don't even need a temporary variable. Just don't try that on
0.9.6 or earlier because it will crash.

See:

http://www.openssl.org/docs/crypto/d2i_X509.html

Steve.
--
Dr Stephen N. Henson. Email, S/MIME and PGP keys: see homepage
OpenSSL project core developer and freelance consultant.
Funding needed! Details on homepage.
Homepage: http://www.drh-consultancy.demon.co.uk
______________________________________________________________________
OpenSSL Project                                 http://www.openssl.org
User Support Mailing List                    [EMAIL PROTECTED]
Automated List Manager                           [EMAIL PROTECTED]

Reply via email to