Coverage Report

Created: 2026-12-01 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libmongocrypt/kms-message/src/hexlify.c
Line
Count
Source
1
/*
2
 * Copyright 2018-present MongoDB, Inc.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *   http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
#include "hexlify.h"
18
19
//
20
21
#include "kms_message_private.h"
22
23
#include <limits.h>
24
#include <stdint.h>
25
#include <stdio.h>
26
#include <stdlib.h>
27
#include <string.h>
28
29
char *
30
hexlify (const uint8_t *buf, size_t len)
31
18.3k
{
32
18.3k
   char *hex_chars = malloc (len * 2 + 1);
33
18.3k
   KMS_ASSERT (hex_chars);
34
35
18.3k
   char *p = hex_chars;
36
18.3k
   size_t i;
37
38
604k
   for (i = 0; i < len; i++) {
39
586k
      KMS_ASSERT (2 == snprintf (p, 3, "%02x", buf[i]));
40
586k
      p += 2;
41
586k
   }
42
43
18.3k
   *p = '\0';
44
45
18.3k
   return hex_chars;
46
18.3k
}
47
48
/* Returns -1 on error. */
49
int
50
unhexlify (const char *in, size_t len)
51
284
{
52
284
   int i;
53
284
   int byte;
54
284
   int64_t total = 0;
55
284
   int64_t multiplier = 1;
56
57
1.83k
   for (i = (int) len - 1; i >= 0; i--) {
58
1.60k
      char c = *(in + i);
59
60
1.60k
      if (c >= '0' && c <= '9') {
61
799
         byte = c - 48;
62
807
      } else if (c >= 'a' && c <= 'f') {
63
416
         byte = c - 97 + 10;
64
416
      } else if (c >= 'A' && c <= 'F') {
65
354
         byte = c - 65 + 10;
66
354
      } else {
67
37
         return -1;
68
37
      }
69
70
1.56k
      total += (int64_t) byte * multiplier;
71
1.56k
      if (total > INT_MAX) {
72
16
         return -1;
73
16
      }
74
1.55k
      multiplier *= 16;
75
1.55k
   }
76
231
   return (int) total;
77
284
}