-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.c
More file actions
74 lines (56 loc) · 1.63 KB
/
utils.c
File metadata and controls
74 lines (56 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
// Created by smirnov on 1/3/22.
//
#include "utils.h"
#include <string.h>
#include <openssl/bio.h>
static unsigned char hex_char_to_bin(unsigned char hex);
int utils_hex_to_bin(const unsigned char *hex, unsigned char *bin, size_t bin_length) {
size_t hex_len = strlen((const char*)hex);
if(hex_len%2 != 0 || hex_len/2 > bin_length) {
return 0;
}
for(int i = 0; i < hex_len; i+=2) {
unsigned char high, low;
high = hex_char_to_bin(hex[i]);
low = hex_char_to_bin(hex[i+1]);
bin[i/2] = (high<<4)|low;
}
return 1;
}
const char *utils_bin_to_hex(const unsigned char *bin, size_t bin_length) {
static char buffer[512];
char *p = buffer;
for(int i=0; i<bin_length; i++) {
p += sprintf(p,"%02x", bin[i]);
}
return buffer;
}
void utils_memory_dump(const unsigned char *data, size_t len) {
BIO *log_buffer = BIO_new(BIO_s_mem());
BIO_dump_indent(log_buffer, (const char*)data, len, 0);
char line[512];
int line_read;
do {
line_read = BIO_gets(log_buffer, line, sizeof(line));
if(line_read > 0) {
if(line[line_read-1] == '\n') {
line[line_read-1] = 0;
}
printf("%s\n", line);
}
} while (line_read > 0);
BIO_free(log_buffer);
}
// Private
static unsigned char hex_char_to_bin(unsigned char hex) {
if(hex >= '0' && hex <= '9') {
return hex - '0';
} else if(hex >='A' && hex <= 'Z') {
return hex - 'A'+10;
} else if(hex >= 'a' && hex <= 'z') {
return hex - 'a'+10;
}
fprintf(stderr, "wrong hex char\n");
exit(0);
}