Limit depth of nested sequences when generating ASN.1
[openssl.git] / crypto / md32_common.h
1 /* crypto/md32_common.h */
2 /* ====================================================================
3  * Copyright (c) 1999-2007 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  *    licensing@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  */
51
52 /*-
53  * This is a generic 32 bit "collector" for message digest algorithms.
54  * Whenever needed it collects input character stream into chunks of
55  * 32 bit values and invokes a block function that performs actual hash
56  * calculations.
57  *
58  * Porting guide.
59  *
60  * Obligatory macros:
61  *
62  * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
63  *      this macro defines byte order of input stream.
64  * HASH_CBLOCK
65  *      size of a unit chunk HASH_BLOCK operates on.
66  * HASH_LONG
67  *      has to be at lest 32 bit wide.
68  * HASH_CTX
69  *      context structure that at least contains following
70  *      members:
71  *              typedef struct {
72  *                      ...
73  *                      HASH_LONG       Nl,Nh;
74  *                      either {
75  *                      HASH_LONG       data[HASH_LBLOCK];
76  *                      unsigned char   data[HASH_CBLOCK];
77  *                      };
78  *                      unsigned int    num;
79  *                      ...
80  *                      } HASH_CTX;
81  *      data[] vector is expected to be zeroed upon first call to
82  *      HASH_UPDATE.
83  * HASH_UPDATE
84  *      name of "Update" function, implemented here.
85  * HASH_TRANSFORM
86  *      name of "Transform" function, implemented here.
87  * HASH_FINAL
88  *      name of "Final" function, implemented here.
89  * HASH_BLOCK_DATA_ORDER
90  *      name of "block" function capable of treating *unaligned* input
91  *      message in original (data) byte order, implemented externally.
92  * HASH_MAKE_STRING
93  *      macro convering context variables to an ASCII hash string.
94  *
95  * MD5 example:
96  *
97  *      #define DATA_ORDER_IS_LITTLE_ENDIAN
98  *
99  *      #define HASH_LONG               MD5_LONG
100  *      #define HASH_CTX                MD5_CTX
101  *      #define HASH_CBLOCK             MD5_CBLOCK
102  *      #define HASH_UPDATE             MD5_Update
103  *      #define HASH_TRANSFORM          MD5_Transform
104  *      #define HASH_FINAL              MD5_Final
105  *      #define HASH_BLOCK_DATA_ORDER   md5_block_data_order
106  *
107  *                                      <appro@fy.chalmers.se>
108  */
109
110 #if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
111 # error "DATA_ORDER must be defined!"
112 #endif
113
114 #ifndef HASH_CBLOCK
115 # error "HASH_CBLOCK must be defined!"
116 #endif
117 #ifndef HASH_LONG
118 # error "HASH_LONG must be defined!"
119 #endif
120 #ifndef HASH_CTX
121 # error "HASH_CTX must be defined!"
122 #endif
123
124 #ifndef HASH_UPDATE
125 # error "HASH_UPDATE must be defined!"
126 #endif
127 #ifndef HASH_TRANSFORM
128 # error "HASH_TRANSFORM must be defined!"
129 #endif
130 #ifndef HASH_FINAL
131 # error "HASH_FINAL must be defined!"
132 #endif
133
134 #ifndef HASH_BLOCK_DATA_ORDER
135 # error "HASH_BLOCK_DATA_ORDER must be defined!"
136 #endif
137
138 /*
139  * Engage compiler specific rotate intrinsic function if available.
140  */
141 #undef ROTATE
142 #ifndef PEDANTIC
143 # if defined(_MSC_VER)
144 #  define ROTATE(a,n)   _lrotl(a,n)
145 # elif defined(__ICC)
146 #  define ROTATE(a,n)   _rotl(a,n)
147 # elif defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
148   /*
149    * Some GNU C inline assembler templates. Note that these are
150    * rotates by *constant* number of bits! But that's exactly
151    * what we need here...
152    *                                    <appro@fy.chalmers.se>
153    */
154 #  if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
155 #   define ROTATE(a,n)  ({ register unsigned int ret;   \
156                                 asm (                   \
157                                 "roll %1,%0"            \
158                                 : "=r"(ret)             \
159                                 : "I"(n), "0"((unsigned int)(a))        \
160                                 : "cc");                \
161                            ret;                         \
162                         })
163 #  elif defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
164         defined(__powerpc) || defined(__ppc__) || defined(__powerpc64__)
165 #   define ROTATE(a,n)  ({ register unsigned int ret;   \
166                                 asm (                   \
167                                 "rlwinm %0,%1,%2,0,31"  \
168                                 : "=r"(ret)             \
169                                 : "r"(a), "I"(n));      \
170                            ret;                         \
171                         })
172 #  elif defined(__s390x__)
173 #   define ROTATE(a,n) ({ register unsigned int ret;    \
174                                 asm ("rll %0,%1,%2"     \
175                                 : "=r"(ret)             \
176                                 : "r"(a), "I"(n));      \
177                           ret;                          \
178                         })
179 #  endif
180 # endif
181 #endif                          /* PEDANTIC */
182
183 #ifndef ROTATE
184 # define ROTATE(a,n)     (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
185 #endif
186
187 #if defined(DATA_ORDER_IS_BIG_ENDIAN)
188
189 # ifndef PEDANTIC
190 #  if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
191 #   if ((defined(__i386) || defined(__i386__)) && !defined(I386_ONLY)) || \
192       (defined(__x86_64) || defined(__x86_64__))
193 #    if !defined(B_ENDIAN)
194     /*
195      * This gives ~30-40% performance improvement in SHA-256 compiled
196      * with gcc [on P4]. Well, first macro to be frank. We can pull
197      * this trick on x86* platforms only, because these CPUs can fetch
198      * unaligned data without raising an exception.
199      */
200 #     define HOST_c2l(c,l)        ({ unsigned int r=*((const unsigned int *)(c)); \
201                                    asm ("bswapl %0":"=r"(r):"0"(r));    \
202                                    (c)+=4; (l)=r;                       })
203 #     define HOST_l2c(l,c)        ({ unsigned int r=(l);                  \
204                                    asm ("bswapl %0":"=r"(r):"0"(r));    \
205                                    *((unsigned int *)(c))=r; (c)+=4; r; })
206 #    endif
207 #   elif defined(__aarch64__)
208 #    if defined(__BYTE_ORDER__)
209 #     if defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
210 #      define HOST_c2l(c,l)      ({ unsigned int r;              \
211                                    asm ("rev    %w0,%w1"        \
212                                         :"=r"(r)                \
213                                         :"r"(*((const unsigned int *)(c))));\
214                                    (c)+=4; (l)=r;               })
215 #      define HOST_l2c(l,c)      ({ unsigned int r;              \
216                                    asm ("rev    %w0,%w1"        \
217                                         :"=r"(r)                \
218                                         :"r"((unsigned int)(l)));\
219                                    *((unsigned int *)(c))=r; (c)+=4; r; })
220 #     elif defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__==__ORDER_BIG_ENDIAN__
221 #      define HOST_c2l(c,l)      ((l)=*((const unsigned int *)(c)), (c)+=4, (l))
222 #      define HOST_l2c(l,c)      (*((unsigned int *)(c))=(l), (c)+=4, (l))
223 #     endif
224 #    endif
225 #   endif
226 #  endif
227 #  if defined(__s390__) || defined(__s390x__)
228 #   define HOST_c2l(c,l) ((l)=*((const unsigned int *)(c)), (c)+=4, (l))
229 #   define HOST_l2c(l,c) (*((unsigned int *)(c))=(l), (c)+=4, (l))
230 #  endif
231 # endif
232
233 # ifndef HOST_c2l
234 #  define HOST_c2l(c,l)   (l =(((unsigned long)(*((c)++)))<<24),          \
235                          l|=(((unsigned long)(*((c)++)))<<16),          \
236                          l|=(((unsigned long)(*((c)++)))<< 8),          \
237                          l|=(((unsigned long)(*((c)++)))    )           )
238 # endif
239 # ifndef HOST_l2c
240 #  define HOST_l2c(l,c)   (*((c)++)=(unsigned char)(((l)>>24)&0xff),      \
241                          *((c)++)=(unsigned char)(((l)>>16)&0xff),      \
242                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),      \
243                          *((c)++)=(unsigned char)(((l)    )&0xff),      \
244                          l)
245 # endif
246
247 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
248
249 # ifndef PEDANTIC
250 #  if defined(__GNUC__) && __GNUC__>=2 && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
251 #   if defined(__s390x__)
252 #    define HOST_c2l(c,l)        ({ asm ("lrv    %0,%1"                  \
253                                    :"=d"(l) :"m"(*(const unsigned int *)(c)));\
254                                    (c)+=4; (l);                         })
255 #    define HOST_l2c(l,c)        ({ asm ("strv   %1,%0"                  \
256                                    :"=m"(*(unsigned int *)(c)) :"d"(l));\
257                                    (c)+=4; (l);                         })
258 #   endif
259 #  endif
260 #  if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
261 #   ifndef B_ENDIAN
262     /* See comment in DATA_ORDER_IS_BIG_ENDIAN section. */
263 #    define HOST_c2l(c,l)        ((l)=*((const unsigned int *)(c)), (c)+=4, l)
264 #    define HOST_l2c(l,c)        (*((unsigned int *)(c))=(l), (c)+=4, l)
265 #   endif
266 #  endif
267 # endif
268
269 # ifndef HOST_c2l
270 #  define HOST_c2l(c,l)   (l =(((unsigned long)(*((c)++)))    ),          \
271                          l|=(((unsigned long)(*((c)++)))<< 8),          \
272                          l|=(((unsigned long)(*((c)++)))<<16),          \
273                          l|=(((unsigned long)(*((c)++)))<<24)           )
274 # endif
275 # ifndef HOST_l2c
276 #  define HOST_l2c(l,c)   (*((c)++)=(unsigned char)(((l)    )&0xff),      \
277                          *((c)++)=(unsigned char)(((l)>> 8)&0xff),      \
278                          *((c)++)=(unsigned char)(((l)>>16)&0xff),      \
279                          *((c)++)=(unsigned char)(((l)>>24)&0xff),      \
280                          l)
281 # endif
282
283 #endif
284
285 /*
286  * Time for some action:-)
287  */
288
289 int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len)
290 {
291     const unsigned char *data = data_;
292     unsigned char *p;
293     HASH_LONG l;
294     size_t n;
295
296     if (len == 0)
297         return 1;
298
299     l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL;
300     /*
301      * 95-05-24 eay Fixed a bug with the overflow handling, thanks to Wei Dai
302      * <weidai@eskimo.com> for pointing it out.
303      */
304     if (l < c->Nl)              /* overflow */
305         c->Nh++;
306     c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on
307                                        * 16-bit */
308     c->Nl = l;
309
310     n = c->num;
311     if (n != 0) {
312         p = (unsigned char *)c->data;
313
314         if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) {
315             memcpy(p + n, data, HASH_CBLOCK - n);
316             HASH_BLOCK_DATA_ORDER(c, p, 1);
317             n = HASH_CBLOCK - n;
318             data += n;
319             len -= n;
320             c->num = 0;
321             memset(p, 0, HASH_CBLOCK); /* keep it zeroed */
322         } else {
323             memcpy(p + n, data, len);
324             c->num += (unsigned int)len;
325             return 1;
326         }
327     }
328
329     n = len / HASH_CBLOCK;
330     if (n > 0) {
331         HASH_BLOCK_DATA_ORDER(c, data, n);
332         n *= HASH_CBLOCK;
333         data += n;
334         len -= n;
335     }
336
337     if (len != 0) {
338         p = (unsigned char *)c->data;
339         c->num = (unsigned int)len;
340         memcpy(p, data, len);
341     }
342     return 1;
343 }
344
345 void HASH_TRANSFORM(HASH_CTX *c, const unsigned char *data)
346 {
347     HASH_BLOCK_DATA_ORDER(c, data, 1);
348 }
349
350 int HASH_FINAL(unsigned char *md, HASH_CTX *c)
351 {
352     unsigned char *p = (unsigned char *)c->data;
353     size_t n = c->num;
354
355     p[n] = 0x80;                /* there is always room for one */
356     n++;
357
358     if (n > (HASH_CBLOCK - 8)) {
359         memset(p + n, 0, HASH_CBLOCK - n);
360         n = 0;
361         HASH_BLOCK_DATA_ORDER(c, p, 1);
362     }
363     memset(p + n, 0, HASH_CBLOCK - 8 - n);
364
365     p += HASH_CBLOCK - 8;
366 #if   defined(DATA_ORDER_IS_BIG_ENDIAN)
367     (void)HOST_l2c(c->Nh, p);
368     (void)HOST_l2c(c->Nl, p);
369 #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
370     (void)HOST_l2c(c->Nl, p);
371     (void)HOST_l2c(c->Nh, p);
372 #endif
373     p -= HASH_CBLOCK;
374     HASH_BLOCK_DATA_ORDER(c, p, 1);
375     c->num = 0;
376     memset(p, 0, HASH_CBLOCK);
377
378 #ifndef HASH_MAKE_STRING
379 # error "HASH_MAKE_STRING must be defined!"
380 #else
381     HASH_MAKE_STRING(c, md);
382 #endif
383
384     return 1;
385 }
386
387 #ifndef MD32_REG_T
388 # if defined(__alpha) || defined(__sparcv9) || defined(__mips)
389 #  define MD32_REG_T long
390 /*
391  * This comment was originaly written for MD5, which is why it
392  * discusses A-D. But it basically applies to all 32-bit digests,
393  * which is why it was moved to common header file.
394  *
395  * In case you wonder why A-D are declared as long and not
396  * as MD5_LONG. Doing so results in slight performance
397  * boost on LP64 architectures. The catch is we don't
398  * really care if 32 MSBs of a 64-bit register get polluted
399  * with eventual overflows as we *save* only 32 LSBs in
400  * *either* case. Now declaring 'em long excuses the compiler
401  * from keeping 32 MSBs zeroed resulting in 13% performance
402  * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
403  * Well, to be honest it should say that this *prevents*
404  * performance degradation.
405  *                              <appro@fy.chalmers.se>
406  */
407 # else
408 /*
409  * Above is not absolute and there are LP64 compilers that
410  * generate better code if MD32_REG_T is defined int. The above
411  * pre-processor condition reflects the circumstances under which
412  * the conclusion was made and is subject to further extension.
413  *                              <appro@fy.chalmers.se>
414  */
415 #  define MD32_REG_T int
416 # endif
417 #endif