]> source.dussan.org Git - rspamd.git/commitdiff
Add hex encoding/decoding routines
authorVsevolod Stakhov <vsevolod@highsecure.ru>
Tue, 2 Feb 2016 12:47:10 +0000 (12:47 +0000)
committerVsevolod Stakhov <vsevolod@highsecure.ru>
Tue, 2 Feb 2016 12:47:10 +0000 (12:47 +0000)
src/libutil/str_util.c
src/libutil/str_util.h

index d3851c89c4457b3884d3588f2ca29a32e4a93882..17039bd6c8f377b53eb60faaf9f93ea3bd56ef70 100644 (file)
@@ -1274,6 +1274,77 @@ rspamd_string_find_eoh (GString *input)
        return -1;
 }
 
+gchar *
+rspamd_encode_hex (const guchar *in, gsize inlen)
+{
+       gchar *out, *o;
+       const guchar *p;
+       gsize outlen = inlen * 2 + 1;
+       static const gchar hexdigests[16] = "0123456789ABCDEF";
+
+       if (in == NULL) {
+               return NULL;
+       }
+
+       out = g_malloc (outlen);
+       o = out;
+       p = in;
+
+       while (inlen > 0) {
+               *o++ = hexdigests[((*p >> 4) & 0xFF)];
+               *o++ = hexdigests[((*p++) & 0xFF)];
+               inlen --;
+       }
+
+       *o = '\0';
+
+       return out;
+}
+
+
+guchar*
+rspamd_decode_hex (const gchar *in, gsize inlen)
+{
+       guchar *out, *o, ret;
+       const gchar *p;
+       gchar c;
+       gsize outlen = (inlen / 2 + inlen % 2) + 1;
+
+       if (in == NULL) {
+               return NULL;
+       }
+
+       out = g_malloc (outlen);
+       o = out;
+       p = in;
+
+       /* We ignore trailing chars if we have not even input */
+       inlen = inlen - inlen % 2;
+
+       while (inlen > 0) {
+               c = *p++;
+
+               if      (c >= '0' && c <= '9') ret = c - '0';
+               else if (c >= 'A' && c <= 'F') ret = c - 'A' + 10;
+               else if (c >= 'a' && c <= 'f') ret = c - 'a' + 10;
+
+               c = *p++;
+               ret *= 16;
+
+               if      (c >= '0' && c <= '9') ret += c - '0';
+               else if (c >= 'A' && c <= 'F') ret += c - 'A' + 10;
+               else if (c >= 'a' && c <= 'f') ret += c - 'a' + 10;
+
+               *o++ = ret;
+
+               inlen -= 2;
+       }
+
+       *o = '\0';
+
+       return out;
+}
+
 /*
  * GString ucl emitting functions
  */
index da794bc16b23298df8b228432c0ad8ccab24c487..03798c80e299cb10cf3088211281757e0b1a14d2 100644 (file)
@@ -124,6 +124,22 @@ gchar * rspamd_encode_base32 (const guchar *in, gsize inlen);
  */
 guchar* rspamd_decode_base32 (const gchar *in, gsize inlen, gsize *outlen);
 
+/**
+ * Encode string using hex encoding
+ * @param in input
+ * @param inlen input length
+ * @return freshly allocated base32 encoding of a specified string
+ */
+gchar * rspamd_encode_hex (const guchar *in, gsize inlen);
+
+/**
+ * Decode string using hex encoding
+ * @param in input
+ * @param inlen input length
+ * @return freshly allocated base32 decoded value or NULL if input is invalid
+ */
+guchar* rspamd_decode_hex (const gchar *in, gsize inlen);
+
 /**
  * Encode string using base64 encoding
  * @param in input