e8aa7461b4900c0717be6f5a00cd2d0311d0a2e8
[openssl.git] / apps / ecdsa.c
1 /* apps/ecdsa.c */
2 /* ====================================================================
3  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer. 
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
56  * All rights reserved.
57  *
58  * This package is an SSL implementation written
59  * by Eric Young (eay@cryptsoft.com).
60  * The implementation was written so as to conform with Netscapes SSL.
61  * 
62  * This library is free for commercial and non-commercial use as long as
63  * the following conditions are aheared to.  The following conditions
64  * apply to all code found in this distribution, be it the RC4, RSA,
65  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
66  * included with this distribution is covered by the same copyright terms
67  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
68  * 
69  * Copyright remains Eric Young's, and as such any Copyright notices in
70  * the code are not to be removed.
71  * If this package is used in a product, Eric Young should be given attribution
72  * as the author of the parts of the library used.
73  * This can be in the form of a textual message at program startup or
74  * in documentation (online or textual) provided with the package.
75  * 
76  * Redistribution and use in source and binary forms, with or without
77  * modification, are permitted provided that the following conditions
78  * are met:
79  * 1. Redistributions of source code must retain the copyright
80  *    notice, this list of conditions and the following disclaimer.
81  * 2. Redistributions in binary form must reproduce the above copyright
82  *    notice, this list of conditions and the following disclaimer in the
83  *    documentation and/or other materials provided with the distribution.
84  * 3. All advertising materials mentioning features or use of this software
85  *    must display the following acknowledgement:
86  *    "This product includes cryptographic software written by
87  *     Eric Young (eay@cryptsoft.com)"
88  *    The word 'cryptographic' can be left out if the rouines from the library
89  *    being used are not cryptographic related :-).
90  * 4. If you include any Windows specific code (or a derivative thereof) from 
91  *    the apps directory (application code) you must include an acknowledgement:
92  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
93  * 
94  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
95  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
96  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
97  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
98  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
99  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
100  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
101  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
102  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
103  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
104  * SUCH DAMAGE.
105  * 
106  * The licence and distribution terms for any publically available version or
107  * derivative of this code cannot be changed.  i.e. this code cannot simply be
108  * copied and put under another distribution licence
109  * [including the GNU Public Licence.]
110  */
111
112 #ifndef OPENSSL_NO_ECDSA
113 #include <stdio.h>
114 #include <stdlib.h>
115 #include <string.h>
116 #include <time.h>
117 #include "apps.h"
118 #include <openssl/bio.h>
119 #include <openssl/err.h>
120 #include <openssl/ecdsa.h>
121 #include <openssl/evp.h>
122 #include <openssl/x509.h>
123 #include <openssl/pem.h>
124
125 #undef PROG
126 #define PROG    ecdsa_main
127
128 /* -inform arg  - input format - default PEM (one of DER, NET or PEM)
129  * -outform arg - output format - default PEM
130  * -in arg      - input file - default stdin
131  * -out arg     - output file - default stdout
132  * -des         - encrypt output if PEM format with DES in cbc mode
133  * -des3        - encrypt output if PEM format
134  * -idea        - encrypt output if PEM format
135  * -text        - print a text version
136  * -pub         - print the ECDSA public key
137  * -compressed  - print the public key in compressed form ( default )   
138  * -hybrid      - print the public key in hybrid form
139  * -uncompressed - print the public key in uncompressed form
140  *                the last three options ( compressed, hybrid and uncompressed )
141  *                are only used if the "-pub" option is also selected.
142  *                For a precise description of the the meaning of compressed,
143  *                hybrid and uncompressed please refer to the X9.62 standart.
144  *                All three forms represents ways to express the ecdsa public
145  *                key ( a point on a elliptic curve ) as octet string. Let len be
146  *                the length ( in bytes ) of an element of the field over which
147  *                the curve is defined, then a compressed octet string has the form
148  *                0x02 + result of BN_bn2bin() of the x coordinate of the public key
149  */
150
151 int MAIN(int, char **);
152
153 int MAIN(int argc, char **argv)
154 {
155         ENGINE  *e = NULL;
156         int     ret = 1;
157         ECDSA   *ecdsa = NULL;
158         int     i, badops = 0;
159         const EVP_CIPHER *enc = NULL;
160         BIO     *in = NULL, *out = NULL;
161         int     informat, outformat, text=0, noout=0;
162         int     pubin = 0, pubout = 0;
163         char    *infile, *outfile, *prog, *engine;
164         char    *passargin = NULL, *passargout = NULL;
165         char    *passin = NULL, *passout = NULL;
166         int     pub = 0, point_form = 0;
167         unsigned char *buffer = NULL;
168         unsigned int  buf_len = 0;
169         BIGNUM  *tmp_bn = NULL;
170
171         apps_startup();
172
173         if (bio_err == NULL)
174                 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
175                         BIO_set_fp(bio_err, stderr, BIO_NOCLOSE|BIO_FP_TEXT);
176
177         engine = NULL;
178         infile = NULL;
179         outfile = NULL;
180         informat = FORMAT_PEM;
181         outformat = FORMAT_PEM;
182
183         prog = argv[0];
184         argc--;
185         argv++;
186         while (argc >= 1)
187         {
188                 if (strcmp(*argv,"-inform") == 0)
189                 {
190                         if (--argc < 1) goto bad;
191                         informat=str2fmt(*(++argv));
192                 }
193                 else if (strcmp(*argv,"-outform") == 0)
194                 {
195                         if (--argc < 1) goto bad;
196                         outformat=str2fmt(*(++argv));
197                 }
198                 else if (strcmp(*argv,"-in") == 0)
199                 {
200                         if (--argc < 1) goto bad;
201                         infile= *(++argv);
202                 }
203                 else if (strcmp(*argv,"-out") == 0)
204                 {
205                         if (--argc < 1) goto bad;
206                         outfile= *(++argv);
207                 }
208                 else if (strcmp(*argv,"-passin") == 0)
209                 {
210                         if (--argc < 1) goto bad;
211                         passargin= *(++argv);
212                 }
213                 else if (strcmp(*argv,"-passout") == 0)
214                 {
215                         if (--argc < 1) goto bad;
216                         passargout= *(++argv);
217                 }
218                 else if (strcmp(*argv, "-engine") == 0)
219                 {
220                         if (--argc < 1) goto bad;
221                         engine= *(++argv);
222                 }
223                 else if (strcmp(*argv, "-noout") == 0)
224                         noout = 1;
225                 else if (strcmp(*argv, "-text") == 0)
226                         text = 1;
227                 else if (strcmp(*argv, "-pub") == 0)
228                 {
229                         pub = 1;
230                         buffer = (*(argv+1));
231                         if (strcmp(buffer, "compressed") == 0)
232                                 point_form = POINT_CONVERSION_COMPRESSED;
233                         else if (strcmp(buffer, "hybrid") == 0)
234                                 point_form = POINT_CONVERSION_HYBRID;
235                         else if (strcmp(buffer, "uncompressed") == 0)
236                                 point_form = POINT_CONVERSION_UNCOMPRESSED;
237                         if (point_form)
238                         {
239                                 argc--;
240                                 argv++;
241                         }
242                 }
243                 else if (strcmp(*argv, "-pubin") == 0)
244                         pubin=1;
245                 else if (strcmp(*argv, "-pubout") == 0)
246                         pubout=1;
247                 else if ((enc=EVP_get_cipherbyname(&(argv[0][1]))) == NULL)
248                 {
249                         BIO_printf(bio_err,"unknown option %s\n",*argv);
250                         badops=1;
251                         break;
252                 }
253                 argc--;
254                 argv++;
255         }
256
257         if (badops)
258         {
259 bad:
260                 BIO_printf(bio_err, "%s [options] <infile >outfile\n",prog);
261                 BIO_printf(bio_err, "where options are\n");
262                 BIO_printf(bio_err, " -inform arg     input format - DER or PEM\n");
263                 BIO_printf(bio_err, " -outform arg    output format - DER or PEM\n");
264                 BIO_printf(bio_err, " -in arg         input file\n");
265                 BIO_printf(bio_err, " -passin arg     input file pass phrase source\n");
266                 BIO_printf(bio_err, " -out arg        output file\n");
267                 BIO_printf(bio_err, " -passout arg    output file pass phrase source\n");
268                 BIO_printf(bio_err, " -engine e       use engine e, possibly a hardware device.\n");
269                 BIO_printf(bio_err, " -des            encrypt PEM output with cbc des\n");
270                 BIO_printf(bio_err, " -des3           encrypt PEM output with ede cbc des using 168 bit key\n");
271 #ifndef OPENSSL_NO_IDEA
272                 BIO_printf(bio_err, " -idea           encrypt PEM output with cbc idea\n");
273 #endif
274                 BIO_printf(bio_err, " -text           print the key in text\n");
275                 BIO_printf(bio_err, " -noout          don't print key out\n");
276                 BIO_printf(bio_err, " -pub [compressed | hybrid | uncompressed] \n");
277                 BIO_printf(bio_err, "         compressed     print the public key in compressed form ( default )\n");   
278                 BIO_printf(bio_err, "         hybrid         print the public key in hybrid form\n");
279                 BIO_printf(bio_err, "         uncompressed   print the public key in uncompressed form\n");
280                 goto end;
281         }
282
283         ERR_load_crypto_strings();
284
285         e = setup_engine(bio_err, engine, 0);
286
287         if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) 
288         {
289                 BIO_printf(bio_err, "Error getting passwords\n");
290                 goto end;
291         }
292
293         in = BIO_new(BIO_s_file());
294         out = BIO_new(BIO_s_file());
295         if ((in == NULL) || (out == NULL))
296         {
297                 ERR_print_errors(bio_err);
298                 goto end;
299         }
300
301         if (infile == NULL)
302                 BIO_set_fp(in,stdin,BIO_NOCLOSE);
303         else
304         {
305                 if (BIO_read_filename(in,infile) <= 0)
306                 {
307                         perror(infile);
308                         goto end;
309                 }
310         }
311
312         BIO_printf(bio_err,"read ECDSA key\n");
313         if (informat == FORMAT_ASN1) 
314         {
315                 if (pubin) 
316                         ecdsa = d2i_ECDSA_PUBKEY_bio(in, NULL);
317                 else 
318                         ecdsa = d2i_ECDSAPrivateKey_bio(in, NULL);
319         } else if (informat == FORMAT_PEM) 
320         {
321                 if (pubin) 
322                         ecdsa = PEM_read_bio_ECDSA_PUBKEY(in, NULL, NULL, NULL);
323                 else 
324                         ecdsa = PEM_read_bio_ECDSAPrivateKey(in, NULL, NULL, passin);
325         } else
326         {
327                 BIO_printf(bio_err, "bad input format specified for key\n");
328                 goto end;
329         }
330         if (ecdsa == NULL)
331         {
332                 BIO_printf(bio_err,"unable to load Key\n");
333                 ERR_print_errors(bio_err);
334                 goto end;
335         }
336
337         if (outfile == NULL)
338         {
339                 BIO_set_fp(out, stdout, BIO_NOCLOSE);
340 #ifdef OPENSSL_SYS_VMS
341                 {
342                         BIO *tmpbio = BIO_new(BIO_f_linebuffer());
343                         out = BIO_push(tmpbio, out);
344                 }
345 #endif
346         }
347         else
348         {
349                 if (BIO_write_filename(out, outfile) <= 0)
350                 {
351                         perror(outfile);
352                         goto end;
353                 }
354         }
355
356         if (text) 
357                 if (!ECDSA_print(out, ecdsa, 0))
358                 {
359                         perror(outfile);
360                         ERR_print_errors(bio_err);
361                         goto end;
362                 }
363
364         if (pub)
365         {
366                 fprintf(stdout, "Public Key (");
367                 if (point_form == POINT_CONVERSION_COMPRESSED)
368                         fprintf(stdout, "COMPRESSED");
369                 else if (point_form == POINT_CONVERSION_UNCOMPRESSED)
370                         fprintf(stdout, "UNCOMPRESSED");
371                 else if (point_form == POINT_CONVERSION_HYBRID)
372                         fprintf(stdout, "HYBRID");
373                 fprintf(stdout, ")=");
374                 buf_len = EC_POINT_point2oct(ecdsa->group, EC_GROUP_get0_generator(ecdsa->group),
375                                              point_form, NULL, 0, NULL);
376                 if (!buf_len)
377                 {
378                         BIO_printf(bio_err,"invalid public key length\n");
379                         ERR_print_errors(bio_err);
380                         goto end;
381                 }
382                 if ((tmp_bn = BN_new()) == NULL ||
383                     (buffer = OPENSSL_malloc(buf_len)) == NULL) goto end;
384                 if (!EC_POINT_point2oct(ecdsa->group, EC_GROUP_get0_generator(ecdsa->group),
385                                              point_form, buffer, buf_len, NULL) ||
386                     !BN_bin2bn(buffer, buf_len, tmp_bn))
387                 {
388                         BIO_printf(bio_err,"can not encode public key\n");
389                         ERR_print_errors(bio_err);
390                         OPENSSL_free(buffer);
391                         goto end;
392                 }
393                 BN_print(out, tmp_bn);
394                 fprintf(stdout,"\n");
395         }
396
397         if (noout) 
398                 goto end;
399         BIO_printf(bio_err, "writing ECDSA key\n");
400         if (outformat == FORMAT_ASN1) 
401         {
402                 if(pubin || pubout) 
403                         i = i2d_ECDSA_PUBKEY_bio(out, ecdsa);
404                 else 
405                         i = i2d_ECDSAPrivateKey_bio(out, ecdsa);
406         } else if (outformat == FORMAT_PEM) 
407         {
408                 if(pubin || pubout)
409                         i = PEM_write_bio_ECDSA_PUBKEY(out, ecdsa);
410                 else 
411                         i = PEM_write_bio_ECDSAPrivateKey(out, ecdsa, enc,
412                                                         NULL, 0, NULL, passout);
413         } else 
414         {
415                 BIO_printf(bio_err, "bad output format specified for outfile\n");
416                 goto end;
417         }
418         if (!i)
419         {
420                 BIO_printf(bio_err, "unable to write private key\n");
421                 ERR_print_errors(bio_err);
422         }
423         else
424                 ret=0;
425 end:
426         if (in)         BIO_free(in);
427         if (out)        BIO_free_all(out);
428         if (ecdsa)      ECDSA_free(ecdsa);
429         if (tmp_bn)     BN_free(tmp_bn);
430         if (passin)     OPENSSL_free(passin);
431         if (passout)    OPENSSL_free(passout);
432         apps_shutdown();
433         EXIT(ret);
434 }
435 #endif