tImplement base64_decode() - sick - sign and check files using ed25519
(HTM) git clone git://z3bra.org/sick
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) README
(DIR) LICENSE
---
(DIR) commit 8607d9671280e57b2dac351bf74ad3b4292bd586
(DIR) parent 565aac4be8c959bd7627836c2dae8823abca449a
(HTM) Author: z3bra <willyatmailoodotorg>
Date: Tue, 10 May 2016 19:39:01 +0200
Implement base64_decode()
Diffstat:
M base64.c | 34 ++++++++++++++++++++++++++++---
M base64.h | 1 +
2 files changed, 32 insertions(+), 3 deletions(-)
---
(DIR) diff --git a/base64.c b/base64.c
t@@ -3,6 +3,7 @@
#include <string.h>
#include <stdint.h>
#include <unistd.h>
+#include <limits.h>
#include "base64.h"
t@@ -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)
{
t@@ -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;
t@@ -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;
}
(DIR) diff --git a/base64.h b/base64.h
t@@ -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);