aboutsummaryrefslogtreecommitdiff
path: root/utils.h
diff options
context:
space:
mode:
authorToni Uhlig <matzeton@googlemail.com>2020-10-05 21:19:18 +0200
committerToni Uhlig <matzeton@googlemail.com>2020-10-05 21:34:24 +0200
commit180ad72e3f6d0efd01a38800efc3ed67e07b9592 (patch)
tree1938cec760a15cfa38e9ff50e5f1ff21006aae4f /utils.h
parent77d148bc55d1f87c5f6eb55e099c72008423a27f (diff)
Added support for entropy calculation.
* Currently used for encryption on function level. Signed-off-by: Toni Uhlig <matzeton@googlemail.com>
Diffstat (limited to 'utils.h')
-rw-r--r--utils.h51
1 files changed, 51 insertions, 0 deletions
diff --git a/utils.h b/utils.h
new file mode 100644
index 0000000..fa0e2e0
--- /dev/null
+++ b/utils.h
@@ -0,0 +1,51 @@
+#ifndef UTILS_H
+#define UTILS_H 1
+
+#include <math.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#define MAXLEN 961 // maximum string length
+
+static inline size_t makehist(unsigned char const * const buf, ssize_t * const hist, size_t len) {
+ ssize_t wherechar[256];
+ size_t i, histlen;
+ histlen = 0;
+ for (i = 0; i < 256; i++)
+ wherechar[i] = -1;
+ for (i = 0; i < len; i++) {
+ if (wherechar[buf[i]] == -1) {
+ wherechar[(int)buf[i]] = histlen;
+ histlen++;
+ }
+ hist[wherechar[(int)buf[i]]]++;
+ }
+ return histlen;
+}
+
+static inline double entropy(ssize_t * const hist, size_t histlen, size_t len) {
+ size_t i;
+ double H;
+ H = 0.0;
+ for (i = 0; i < histlen; i++) {
+ H -= (double)hist[i] / len * log2((double)hist[i] / len);
+ }
+ return H;
+}
+
+static inline double entropy_from_buffer(unsigned char const * const buffer, size_t size)
+{
+ ssize_t * const hist_array = malloc(size * sizeof(*hist_array));
+
+ if (!hist_array) {
+ return -1.0;
+ }
+
+ size_t hist_length = makehist(buffer, hist_array, size);
+ double entr = entropy(hist_array, hist_length, size);
+
+ free(hist_array);
+ return entr;
+}
+
+#endif