summaryrefslogtreecommitdiff
path: root/src/core/utilities.c
blob: 969e36bac778f8c6199482fe27e4edb7e1bab3c6 (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* BSD-2-Clause license
 * 
 * Copyright (c) 2018-2023 NST <www.newinfosec.ru>, sss <sss at dark-alexandr dot net>. 
 * 
 */

#include <stdbool.h>
#include <stdint.h>
#include <sys/stat.h>

#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <openssl/evp.h>

#include <openssl/sha.h>

bool
is_regular_file(const char *path)
{
	struct stat path_stat;
	stat(path, &path_stat);
	return S_ISREG(path_stat.st_mode);
}

bool
is_directory(const char *path)
{
	struct stat path_stat;
	stat(path, &path_stat);
	return S_ISDIR(path_stat.st_mode);
}

bool
sha1(uint8_t *dst, const uint8_t *src, size_t src_length)
{
	SHA_CTX ctx = {0};
	if (!SHA1_Init(&ctx))
	{
		return false;
	}
	if (!SHA1_Update(&ctx, src, src_length))
	{
		return false;
	}
	if (!SHA1_Final(dst, &ctx))
	{
		return false;
	}
	return true;
}

void
hex_print(uint8_t *buf, size_t buf_len)
{
	size_t p;
	for (p = 0; p < buf_len; ++p)
	{
		if (!p)
		{
			printf("00: ");
		}
		if (p && !(p % 8))
		{
			printf("| ");
		}
		if (p && !(p % 16))
		{
			size_t pp = p - 16;
			for (; pp < p; ++pp)
			{
				printf("%c", ((char *)(buf))[pp]);
			}
			printf("\n%lx: ", p);
		}
		printf("%x ", ((char *)(buf))[p]);
	}
}

char
random_ascii_character()
{
	/* use whole ascii table of printable characters */
	char c;
get_new_char:
	c = ((rand() % 94) + 32);
	while (!c)
		goto get_new_char;
	return c;
}

char *
random_ascii_string(char *buf, const size_t len)
{
	size_t i = 0;
	if (!buf)
	{
		return 0;
	}
	for (; i < len; ++i)
	{
		buf[i] = random_ascii_character();
	}
	buf[len] = 0;
	return buf;
}

void
random_bytes(uint8_t *buf, size_t buf_len)
{
	size_t i = 0;
	for (; i < buf_len; ++i)
	{
		buf[i] = rand();
	}
}