2 * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "internal/cryptlib.h"
12 #include <openssl/asn1t.h>
13 #include <openssl/bn.h>
16 * Custom primitive type for long handling. This converts between an
17 * ASN1_INTEGER and a long directly.
20 static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
21 static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
23 static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype,
25 static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
26 int utype, char *free_cont, const ASN1_ITEM *it);
27 static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it,
28 int indent, const ASN1_PCTX *pctx);
30 static ASN1_PRIMITIVE_FUNCS long_pf = {
34 long_free, /* Clear should set to initial value */
41 ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, ASN1_LONG_UNDEF, "LONG"
44 ASN1_ITEM_start(ZLONG)
45 ASN1_ITYPE_PRIMITIVE, V_ASN1_INTEGER, NULL, 0, &long_pf, 0, "ZLONG"
48 static int long_new(ASN1_VALUE **pval, const ASN1_ITEM *it)
50 *(long *)pval = it->size;
54 static void long_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
56 *(long *)pval = it->size;
59 static int long_i2c(ASN1_VALUE **pval, unsigned char *cont, int *putype,
65 /* this exists to bypass broken gcc optimization */
66 char *cp = (char *)pval;
68 /* use memcpy, because we may not be long aligned */
69 memcpy(<mp, cp, sizeof(long));
74 * Convert the long to positive: we subtract one if negative so we can
75 * cleanly handle the padding if only the MSB of the leading octet is
79 utmp = -(unsigned long)ltmp - 1;
82 clen = BN_num_bits_word(utmp);
83 /* If MSB of leading octet set we need to pad */
89 /* Convert number of bits to number of octets */
90 clen = (clen + 7) >> 3;
94 *cont++ = (ltmp < 0) ? 0xff : 0;
95 for (i = clen - 1; i >= 0; i--) {
96 cont[i] = (unsigned char)(utmp & 0xff);
105 static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
106 int utype, char *free_cont, const ASN1_ITEM *it)
110 unsigned long utmp = 0;
111 char *cp = (char *)pval;
112 if (len > (int)sizeof(long)) {
113 ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG);
116 /* Is it negative? */
117 if (len && (cont[0] & 0x80))
122 for (i = 0; i < len; i++) {
125 utmp |= cont[i] ^ 0xff;
134 if (ltmp == it->size) {
135 ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG);
138 memcpy(cp, <mp, sizeof(long));
142 static int long_print(BIO *out, ASN1_VALUE **pval, const ASN1_ITEM *it,
143 int indent, const ASN1_PCTX *pctx)
145 return BIO_printf(out, "%ld\n", *(long *)pval);