Debian Codegraph @

src/ltc/pk/asn1/der/utctime/der_decode_utctime.c

raw
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4
5 /**
6 @file der_decode_utctime.c
7 ASN.1 DER, decode a UTCTIME, Tom St Denis
8 */
9
10 #ifdef LTC_DER
11
12 #ifndef LTC_DER_CHAR_TO_INT
13 #define LTC_DER_CHAR_TO_INT
14 static LTC_INLINE int s_char_to_int(unsigned char x)
15 {
16 switch (x) {
17 case '0': return 0;
18 case '1': return 1;
19 case '2': return 2;
20 case '3': return 3;
21 case '4': return 4;
22 case '5': return 5;
23 case '6': return 6;
24 case '7': return 7;
25 case '8': return 8;
26 case '9': return 9;
27 default: return 100;
28 }
29 }
30 #endif
31
32 #define DECODE_V(y, max) \
33 y = s_char_to_int(buf[x])*10 + s_char_to_int(buf[x+1]); \
34 if (y >= max) return CRYPT_INVALID_PACKET; \
35 x += 2;
36
37 /**
38 Decodes a UTC time structure in DER format (reads all 6 valid encoding formats)
39 @param in Input buffer
40 @param inlen Length of input buffer in octets
41 @param out [out] Destination of UTC time structure
42 @return CRYPT_OK if successful
43 */
44 int der_decode_utctime(const unsigned char *in, unsigned long *inlen,
45 ltc_utctime *out)
46 {
47 unsigned char buf[32] = { 0 }; /* initialize as all zeroes */
48 unsigned long x;
49 int y;
50
51 LTC_ARGCHK(in != NULL);
52 LTC_ARGCHK(inlen != NULL);
53 LTC_ARGCHK(out != NULL);
54
55 /* check header */
56 if (*inlen < 2UL || (in[1] >= sizeof(buf)) || ((in[1] + 2UL) > *inlen)) {
57 return CRYPT_INVALID_PACKET;
58 }
59
60 /* decode the string */
61 for (x = 0; x < in[1]; x++) {
62 y = der_ia5_value_decode(in[x+2]);
63 if (y == -1) {
64 return CRYPT_INVALID_PACKET;
65 }
66 buf[x] = y;
67 }
68 *inlen = 2 + x;
69
70
71 /* possible encodings are
72 YYMMDDhhmmZ
73 YYMMDDhhmm+hh'mm'
74 YYMMDDhhmm-hh'mm'
75 YYMMDDhhmmssZ
76 YYMMDDhhmmss+hh'mm'
77 YYMMDDhhmmss-hh'mm'
78
79 So let's do a trivial decode upto [including] mm
80 */
81
82 x = 0;
83 DECODE_V(out->YY, 100);
84 DECODE_V(out->MM, 13);
85 DECODE_V(out->DD, 32);
86 DECODE_V(out->hh, 24);
87 DECODE_V(out->mm, 60);
88
89 /* clear timezone and seconds info */
90 out->off_dir = out->off_hh = out->off_mm = out->ss = 0;
91
92 /* now is it Z, +, - or 0-9 */
93 if (buf[x] == 'Z') {
94 return CRYPT_OK;
95 }
96 if (buf[x] == '+' || buf[x] == '-') {
97 out->off_dir = (buf[x++] == '+') ? 0 : 1;
98 DECODE_V(out->off_hh, 24);
99 DECODE_V(out->off_mm, 60);
100 return CRYPT_OK;
101 }
102
103 /* decode seconds */
104 DECODE_V(out->ss, 60);
105
106 /* now is it Z, +, - */
107 if (buf[x] == 'Z') {
108 return CRYPT_OK;
109 }
110 if (buf[x] == '+' || buf[x] == '-') {
111 out->off_dir = (buf[x++] == '+') ? 0 : 1;
112 DECODE_V(out->off_hh, 24);
113 DECODE_V(out->off_mm, 60);
114 return CRYPT_OK;
115 }
116 return CRYPT_INVALID_PACKET;
117 }
118
119 #undef DECODE_V
120
121 #endif