Path: blob/main/contrib/bearssl/src/x509/asn1enc.c
39507 views
/*1* Copyright (c) 2018 Thomas Pornin <[email protected]>2*3* Permission is hereby granted, free of charge, to any person obtaining4* a copy of this software and associated documentation files (the5* "Software"), to deal in the Software without restriction, including6* without limitation the rights to use, copy, modify, merge, publish,7* distribute, sublicense, and/or sell copies of the Software, and to8* permit persons to whom the Software is furnished to do so, subject to9* the following conditions:10*11* The above copyright notice and this permission notice shall be12* included in all copies or substantial portions of the Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,15* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF16* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND17* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS18* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN19* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN20* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21* SOFTWARE.22*/2324#include "inner.h"2526/* see inner.h */27br_asn1_uint28br_asn1_uint_prepare(const void *xdata, size_t xlen)29{30const unsigned char *x;31br_asn1_uint t;3233x = xdata;34while (xlen > 0 && *x == 0) {35x ++;36xlen --;37}38t.data = x;39t.len = xlen;40t.asn1len = xlen;41if (xlen == 0 || x[0] >= 0x80) {42t.asn1len ++;43}44return t;45}4647/* see inner.h */48size_t49br_asn1_encode_length(void *dest, size_t len)50{51unsigned char *buf;52size_t z;53int i, j;5455buf = dest;56if (len < 0x80) {57if (buf != NULL) {58*buf = len;59}60return 1;61}62i = 0;63for (z = len; z != 0; z >>= 8) {64i ++;65}66if (buf != NULL) {67*buf ++ = 0x80 + i;68for (j = i - 1; j >= 0; j --) {69*buf ++ = len >> (j << 3);70}71}72return i + 1;73}7475/* see inner.h */76size_t77br_asn1_encode_uint(void *dest, br_asn1_uint pp)78{79unsigned char *buf;80size_t lenlen;8182if (dest == NULL) {83return 1 + br_asn1_encode_length(NULL, pp.asn1len) + pp.asn1len;84}85buf = dest;86*buf ++ = 0x02;87lenlen = br_asn1_encode_length(buf, pp.asn1len);88buf += lenlen;89*buf = 0x00;90memcpy(buf + pp.asn1len - pp.len, pp.data, pp.len);91return 1 + lenlen + pp.asn1len;92}939495