xref: /aosp_15_r20/external/mbedtls/tests/src/asn1_helpers.c (revision 62c56f9862f102b96d72393aff6076c951fb8148)
1 /** \file asn1_helpers.c
2  *
3  * \brief Helper functions for tests that manipulate ASN.1 data.
4  */
5 
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
9  */
10 
11 #include <test/helpers.h>
12 #include <test/macros.h>
13 
14 #if defined(MBEDTLS_ASN1_PARSE_C)
15 
16 #include <mbedtls/asn1.h>
17 
mbedtls_test_asn1_skip_integer(unsigned char ** p,const unsigned char * end,size_t min_bits,size_t max_bits,int must_be_odd)18 int mbedtls_test_asn1_skip_integer(unsigned char **p, const unsigned char *end,
19                                    size_t min_bits, size_t max_bits,
20                                    int must_be_odd)
21 {
22     size_t len;
23     size_t actual_bits;
24     unsigned char msb;
25     TEST_EQUAL(mbedtls_asn1_get_tag(p, end, &len,
26                                     MBEDTLS_ASN1_INTEGER),
27                0);
28 
29     /* Check if the retrieved length doesn't extend the actual buffer's size.
30      * It is assumed here, that end >= p, which validates casting to size_t. */
31     TEST_ASSERT(len <= (size_t) (end - *p));
32 
33     /* Tolerate a slight departure from DER encoding:
34      * - 0 may be represented by an empty string or a 1-byte string.
35      * - The sign bit may be used as a value bit. */
36     if ((len == 1 && (*p)[0] == 0) ||
37         (len > 1 && (*p)[0] == 0 && ((*p)[1] & 0x80) != 0)) {
38         ++(*p);
39         --len;
40     }
41     if (min_bits == 0 && len == 0) {
42         return 1;
43     }
44     msb = (*p)[0];
45     TEST_ASSERT(msb != 0);
46     actual_bits = 8 * (len - 1);
47     while (msb != 0) {
48         msb >>= 1;
49         ++actual_bits;
50     }
51     TEST_ASSERT(actual_bits >= min_bits);
52     TEST_ASSERT(actual_bits <= max_bits);
53     if (must_be_odd) {
54         TEST_ASSERT(((*p)[len-1] & 1) != 0);
55     }
56     *p += len;
57     return 1;
58 exit:
59     return 0;
60 }
61 
62 #endif /* MBEDTLS_ASN1_PARSE_C */
63