sick

sign and check files using ed25519
git clone git://z3bra.org/sick
Log | Files | Refs | Submodules | README | LICENSE

commit 8607d9671280e57b2dac351bf74ad3b4292bd586
parent 565aac4be8c959bd7627836c2dae8823abca449a
Author: z3bra <willyatmailoodotorg>
Date:   Tue May 10 19:39:01 2016

Implement base64_decode()

Diffstat:
 base64.c | 34 +++++++++++++++++++++++++++++++---
 base64.h |  1 +
 2 files changed, 32 insertions(+), 3 deletions(-)

diff --git a/base64.c b/base64.c @@ -3,6 +3,7 @@ #include <string.h> #include <stdint.h> #include <unistd.h> +#include <limits.h> #include "base64.h" @@ -10,6 +11,19 @@ const char base64_table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +uint8_t +base64_index(const char *base64, char ch) +{ + uint8_t idx = 0; + + for (idx = 0; idx < 64; idx++) + if (base64[idx] == ch) + break; + + return idx; +} + + size_t base64_encode(char **buf, const unsigned char *msg, size_t len) { @@ -25,7 +39,8 @@ base64_encode(char **buf, const unsigned char *msg, size_t len) for (i = j = 0; i < len; i+=3) { /* concatenate 3 bytes into one 24 bits quantum, or 0 */ - b64 = 0 | (msg[i]<<16); + b64 = 0; + b64 |= (msg[i]<<16); b64 |= ((i+1 < len ? msg[i+1] : 0) << 8); b64 |= i+2 < len ? msg[i+2] : 0; @@ -42,15 +57,28 @@ base64_encode(char **buf, const unsigned char *msg, size_t len) size_t base64_decode(char **buf, const unsigned char *msg, size_t len) { - size_t size; + uint64_t b64; + size_t size, i, j; - size = 1 + (len * 3) / 4; + size = (len * 3) / 4; size -= msg[len - 1] == '=' ? 1 : 0; size -= msg[len - 2] == '=' ? 1 : 0; *buf = malloc(size); memset(*buf, 0, size); + for (i = j = 0; i < len; i+=4) { + b64 = 0; + b64 |= (base64_index(base64_table, msg[i])<<18); + b64 |= (base64_index(base64_table, msg[i+1])<<12); + b64 |= i + 2 < len ? (base64_index(base64_table, msg[i+2])<<6) : 0; + b64 |= i + 3 < len ? (base64_index(base64_table, msg[i+3])) : 0; + + (*buf)[j++] = 255 & (b64>>16); + (*buf)[j++] = 255 & (b64>>8); + (*buf)[j++] = 255 & (b64); + } + return size; } diff --git a/base64.h b/base64.h @@ -1,6 +1,7 @@ #ifndef BASE64_H__ #define BASE64_H__ +uint8_t base64_index(const char *base64, char ch); size_t base64_encode(char **buf, const unsigned char *msg, size_t len); size_t base64_decode(char **buf, const unsigned char *msg, size_t len); size_t base64_fold(FILE *out, char *msg, size_t len, size_t fold);