Deprecate the recursive includes of bn.h from various API headers (asn1.h,
[openssl.git] / crypto / asn1 / a_int.c
1 /* crypto/asn1/a_int.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58
59 #include <stdio.h>
60 #include "cryptlib.h"
61 #include <openssl/asn1.h>
62 #include <openssl/bn.h>
63
64 ASN1_INTEGER *ASN1_INTEGER_dup(ASN1_INTEGER *x)
65 { return M_ASN1_INTEGER_dup(x);}
66
67 int ASN1_INTEGER_cmp(ASN1_INTEGER *x, ASN1_INTEGER *y)
68 { return M_ASN1_INTEGER_cmp(x,y);}
69
70 /* 
71  * This converts an ASN1 INTEGER into its content encoding.
72  * The internal representation is an ASN1_STRING whose data is a big endian
73  * representation of the value, ignoring the sign. The sign is determined by
74  * the type: V_ASN1_INTEGER for positive and V_ASN1_NEG_INTEGER for negative. 
75  *
76  * Positive integers are no problem: they are almost the same as the DER
77  * encoding, except if the first byte is >= 0x80 we need to add a zero pad.
78  *
79  * Negative integers are a bit trickier...
80  * The DER representation of negative integers is in 2s complement form.
81  * The internal form is converted by complementing each octet and finally 
82  * adding one to the result. This can be done less messily with a little trick.
83  * If the internal form has trailing zeroes then they will become FF by the
84  * complement and 0 by the add one (due to carry) so just copy as many trailing 
85  * zeros to the destination as there are in the source. The carry will add one
86  * to the last none zero octet: so complement this octet and add one and finally
87  * complement any left over until you get to the start of the string.
88  *
89  * Padding is a little trickier too. If the first bytes is > 0x80 then we pad
90  * with 0xff. However if the first byte is 0x80 and one of the following bytes
91  * is non-zero we pad with 0xff. The reason for this distinction is that 0x80
92  * followed by optional zeros isn't padded.
93  */
94
95 int i2c_ASN1_INTEGER(ASN1_INTEGER *a, unsigned char **pp)
96         {
97         int pad=0,ret,i,neg;
98         unsigned char *p,*n,pb=0;
99
100         if ((a == NULL) || (a->data == NULL)) return(0);
101         neg=a->type & V_ASN1_NEG;
102         if (a->length == 0)
103                 ret=1;
104         else
105                 {
106                 ret=a->length;
107                 i=a->data[0];
108                 if (!neg && (i > 127)) {
109                         pad=1;
110                         pb=0;
111                 } else if(neg) {
112                         if(i>128) {
113                                 pad=1;
114                                 pb=0xFF;
115                         } else if(i == 128) {
116                         /*
117                          * Special case: if any other bytes non zero we pad:
118                          * otherwise we don't.
119                          */
120                                 for(i = 1; i < a->length; i++) if(a->data[i]) {
121                                                 pad=1;
122                                                 pb=0xFF;
123                                                 break;
124                                 }
125                         }
126                 }
127                 ret+=pad;
128                 }
129         if (pp == NULL) return(ret);
130         p= *pp;
131
132         if (pad) *(p++)=pb;
133         if (a->length == 0) *(p++)=0;
134         else if (!neg) memcpy(p,a->data,(unsigned int)a->length);
135         else {
136                 /* Begin at the end of the encoding */
137                 n=a->data + a->length - 1;
138                 p += a->length - 1;
139                 i = a->length;
140                 /* Copy zeros to destination as long as source is zero */
141                 while(!*n) {
142                         *(p--) = 0;
143                         n--;
144                         i--;
145                 }
146                 /* Complement and increment next octet */
147                 *(p--) = ((*(n--)) ^ 0xff) + 1;
148                 i--;
149                 /* Complement any octets left */
150                 for(;i > 0; i--) *(p--) = *(n--) ^ 0xff;
151         }
152
153         *pp+=ret;
154         return(ret);
155         }
156
157 /* Convert just ASN1 INTEGER content octets to ASN1_INTEGER structure */
158
159 ASN1_INTEGER *c2i_ASN1_INTEGER(ASN1_INTEGER **a, const unsigned char **pp,
160              long len)
161         {
162         ASN1_INTEGER *ret=NULL;
163         const unsigned char *p, *pend;
164         unsigned char *to,*s;
165         int i;
166
167         if ((a == NULL) || ((*a) == NULL))
168                 {
169                 if ((ret=M_ASN1_INTEGER_new()) == NULL) return(NULL);
170                 ret->type=V_ASN1_INTEGER;
171                 }
172         else
173                 ret=(*a);
174
175         p= *pp;
176         pend = p + len;
177
178         /* We must OPENSSL_malloc stuff, even for 0 bytes otherwise it
179          * signifies a missing NULL parameter. */
180         s=(unsigned char *)OPENSSL_malloc((int)len+1);
181         if (s == NULL)
182                 {
183                 i=ERR_R_MALLOC_FAILURE;
184                 goto err;
185                 }
186         to=s;
187         if(!len) {
188                 /* Strictly speaking this is an illegal INTEGER but we
189                  * tolerate it.
190                  */
191                 ret->type=V_ASN1_INTEGER;
192         } else if (*p & 0x80) /* a negative number */
193                 {
194                 ret->type=V_ASN1_NEG_INTEGER;
195                 if ((*p == 0xff) && (len != 1)) {
196                         p++;
197                         len--;
198                 }
199                 i = len;
200                 p += i - 1;
201                 to += i - 1;
202                 while((!*p) && i) {
203                         *(to--) = 0;
204                         i--;
205                         p--;
206                 }
207                 /* Special case: if all zeros then the number will be of
208                  * the form FF followed by n zero bytes: this corresponds to
209                  * 1 followed by n zero bytes. We've already written n zeros
210                  * so we just append an extra one and set the first byte to
211                  * a 1. This is treated separately because it is the only case
212                  * where the number of bytes is larger than len.
213                  */
214                 if(!i) {
215                         *s = 1;
216                         s[len] = 0;
217                         len++;
218                 } else {
219                         *(to--) = (*(p--) ^ 0xff) + 1;
220                         i--;
221                         for(;i > 0; i--) *(to--) = *(p--) ^ 0xff;
222                 }
223         } else {
224                 ret->type=V_ASN1_INTEGER;
225                 if ((*p == 0) && (len != 1))
226                         {
227                         p++;
228                         len--;
229                         }
230                 memcpy(s,p,(int)len);
231         }
232
233         if (ret->data != NULL) OPENSSL_free(ret->data);
234         ret->data=s;
235         ret->length=(int)len;
236         if (a != NULL) (*a)=ret;
237         *pp=pend;
238         return(ret);
239 err:
240         ASN1err(ASN1_F_D2I_ASN1_INTEGER,i);
241         if ((ret != NULL) && ((a == NULL) || (*a != ret)))
242                 M_ASN1_INTEGER_free(ret);
243         return(NULL);
244         }
245
246
247 /* This is a version of d2i_ASN1_INTEGER that ignores the sign bit of
248  * ASN1 integers: some broken software can encode a positive INTEGER
249  * with its MSB set as negative (it doesn't add a padding zero).
250  */
251
252 ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
253              long length)
254         {
255         ASN1_INTEGER *ret=NULL;
256         const unsigned char *p;
257         unsigned char *to,*s;
258         long len;
259         int inf,tag,xclass;
260         int i;
261
262         if ((a == NULL) || ((*a) == NULL))
263                 {
264                 if ((ret=M_ASN1_INTEGER_new()) == NULL) return(NULL);
265                 ret->type=V_ASN1_INTEGER;
266                 }
267         else
268                 ret=(*a);
269
270         p= *pp;
271         inf=ASN1_get_object(&p,&len,&tag,&xclass,length);
272         if (inf & 0x80)
273                 {
274                 i=ASN1_R_BAD_OBJECT_HEADER;
275                 goto err;
276                 }
277
278         if (tag != V_ASN1_INTEGER)
279                 {
280                 i=ASN1_R_EXPECTING_AN_INTEGER;
281                 goto err;
282                 }
283
284         /* We must OPENSSL_malloc stuff, even for 0 bytes otherwise it
285          * signifies a missing NULL parameter. */
286         s=(unsigned char *)OPENSSL_malloc((int)len+1);
287         if (s == NULL)
288                 {
289                 i=ERR_R_MALLOC_FAILURE;
290                 goto err;
291                 }
292         to=s;
293         ret->type=V_ASN1_INTEGER;
294         if(len) {
295                 if ((*p == 0) && (len != 1))
296                         {
297                         p++;
298                         len--;
299                         }
300                 memcpy(s,p,(int)len);
301                 p+=len;
302         }
303
304         if (ret->data != NULL) OPENSSL_free(ret->data);
305         ret->data=s;
306         ret->length=(int)len;
307         if (a != NULL) (*a)=ret;
308         *pp=p;
309         return(ret);
310 err:
311         ASN1err(ASN1_F_D2I_ASN1_UINTEGER,i);
312         if ((ret != NULL) && ((a == NULL) || (*a != ret)))
313                 M_ASN1_INTEGER_free(ret);
314         return(NULL);
315         }
316
317 int ASN1_INTEGER_set(ASN1_INTEGER *a, long v)
318         {
319         int j,k;
320         unsigned int i;
321         unsigned char buf[sizeof(long)+1];
322         long d;
323
324         a->type=V_ASN1_INTEGER;
325         if (a->length < (int)(sizeof(long)+1))
326                 {
327                 if (a->data != NULL)
328                         OPENSSL_free(a->data);
329                 if ((a->data=(unsigned char *)OPENSSL_malloc(sizeof(long)+1)) != NULL)
330                         memset((char *)a->data,0,sizeof(long)+1);
331                 }
332         if (a->data == NULL)
333                 {
334                 ASN1err(ASN1_F_ASN1_INTEGER_SET,ERR_R_MALLOC_FAILURE);
335                 return(0);
336                 }
337         d=v;
338         if (d < 0)
339                 {
340                 d= -d;
341                 a->type=V_ASN1_NEG_INTEGER;
342                 }
343
344         for (i=0; i<sizeof(long); i++)
345                 {
346                 if (d == 0) break;
347                 buf[i]=(int)d&0xff;
348                 d>>=8;
349                 }
350         j=0;
351         for (k=i-1; k >=0; k--)
352                 a->data[j++]=buf[k];
353         a->length=j;
354         return(1);
355         }
356
357 long ASN1_INTEGER_get(ASN1_INTEGER *a)
358         {
359         int neg=0,i;
360         long r=0;
361
362         if (a == NULL) return(0L);
363         i=a->type;
364         if (i == V_ASN1_NEG_INTEGER)
365                 neg=1;
366         else if (i != V_ASN1_INTEGER)
367                 return -1;
368         
369         if (a->length > (int)sizeof(long))
370                 {
371                 /* hmm... a bit ugly */
372                 return(0xffffffffL);
373                 }
374         if (a->data == NULL)
375                 return 0;
376
377         for (i=0; i<a->length; i++)
378                 {
379                 r<<=8;
380                 r|=(unsigned char)a->data[i];
381                 }
382         if (neg) r= -r;
383         return(r);
384         }
385
386 ASN1_INTEGER *BN_to_ASN1_INTEGER(BIGNUM *bn, ASN1_INTEGER *ai)
387         {
388         ASN1_INTEGER *ret;
389         int len,j;
390
391         if (ai == NULL)
392                 ret=M_ASN1_INTEGER_new();
393         else
394                 ret=ai;
395         if (ret == NULL)
396                 {
397                 ASN1err(ASN1_F_BN_TO_ASN1_INTEGER,ERR_R_NESTED_ASN1_ERROR);
398                 goto err;
399                 }
400         if (BN_get_sign(bn))
401                 ret->type = V_ASN1_NEG_INTEGER;
402         else ret->type=V_ASN1_INTEGER;
403         j=BN_num_bits(bn);
404         len=((j == 0)?0:((j/8)+1));
405         if (ret->length < len+4)
406                 {
407                 unsigned char *new_data=OPENSSL_realloc(ret->data, len+4);
408                 if (!new_data)
409                         {
410                         ASN1err(ASN1_F_BN_TO_ASN1_INTEGER,ERR_R_MALLOC_FAILURE);
411                         goto err;
412                         }
413                 ret->data=new_data;
414                 }
415         ret->length=BN_bn2bin(bn,ret->data);
416         /* Correct zero case */
417         if(!ret->length)
418                 {
419                 ret->data[0] = 0;
420                 ret->length = 1;
421                 }
422         return(ret);
423 err:
424         if (ret != ai) M_ASN1_INTEGER_free(ret);
425         return(NULL);
426         }
427
428 BIGNUM *ASN1_INTEGER_to_BN(ASN1_INTEGER *ai, BIGNUM *bn)
429         {
430         BIGNUM *ret;
431
432         if ((ret=BN_bin2bn(ai->data,ai->length,bn)) == NULL)
433                 ASN1err(ASN1_F_ASN1_INTEGER_TO_BN,ASN1_R_BN_LIB);
434         else if(ai->type == V_ASN1_NEG_INTEGER)
435                 BN_set_sign(ret, 1);
436         return(ret);
437         }
438
439 IMPLEMENT_STACK_OF(ASN1_INTEGER)
440 IMPLEMENT_ASN1_SET_OF(ASN1_INTEGER)