rsstats 0.0.1
Redis Enterprise Statistic collector
base64.c
Go to the documentation of this file.
1
21#ifdef HAVE_CONFIG_H
22#include "config.h"
23#endif
24
25#include "base64.h"
26
27#include <stdlib.h>
28#include <stdio.h> /* perror */
29#include <string.h>
30
31static char base46_map[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
32 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
33 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
34 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
35 '3', '4', '5', '6', '7', '8', '9', '+', '/'
36 };
37
38
39char* base64_encode(char* plain) {
40 unsigned char counts = 0;
41 char buffer[3];
42 char* cipher = malloc(strlen(plain) * 4 / 3 + 4);
43 int i = 0, c = 0;
44
45 if (NULL==cipher) {
46 perror("base64_encode");
47 return NULL;
48 }
49
50 for(i = 0; plain[i] != '\0'; i++) {
51 buffer[counts++] = plain[i];
52 if(counts == 3) {
53 cipher[c++] = base46_map[buffer[0] >> 2];
54 cipher[c++] = base46_map[((buffer[0] & 0x03) << 4) + (buffer[1] >> 4)];
55 cipher[c++] = base46_map[((buffer[1] & 0x0f) << 2) + (buffer[2] >> 6)];
56 cipher[c++] = base46_map[buffer[2] & 0x3f];
57 counts = 0;
58 }
59 }
60
61 if(counts > 0) {
62 cipher[c++] = base46_map[buffer[0] >> 2];
63 if(counts == 1) {
64 cipher[c++] = base46_map[(buffer[0] & 0x03) << 4];
65 cipher[c++] = '=';
66 } else { // if counts == 2
67 cipher[c++] = base46_map[((buffer[0] & 0x03) << 4) + (buffer[1] >> 4)];
68 cipher[c++] = base46_map[(buffer[1] & 0x0f) << 2];
69 }
70 cipher[c++] = '=';
71 }
72
73 cipher[c] = '\0'; /* string padding character */
74 return cipher;
75}
76
77char* base64_decode(char* cipher) {
78
79 unsigned char counts = 0;
80 char buffer[4];
81 char* plain = malloc(strlen(cipher) * 3 / 4 + 1);
82 int i = 0, p = 0;
83
84 if (NULL==plain) {
85 perror("base64_decode");
86 return NULL;
87 }
88
89 for(i = 0; cipher[i] != '\0'; i++) {
90 unsigned char k;
91 for(k = 0 ; k < 64 && base46_map[k] != cipher[i]; k++);
92 buffer[counts++] = k;
93 if(counts == 4) {
94 plain[p++] = (buffer[0] << 2) + (buffer[1] >> 4);
95 if(buffer[2] != 64)
96 plain[p++] = (buffer[1] << 4) + (buffer[2] >> 2);
97 if(buffer[3] != 64)
98 plain[p++] = (buffer[2] << 6) + buffer[3];
99 counts = 0;
100 }
101 }
102
103 plain[p] = '\0'; /* string padding character */
104 return plain;
105}
106
107/* vim: set tw=80: */
char * base64_encode(char *plain)
Encode a zero terminated C string in Base64.
Definition: base64.c:39
char * base64_decode(char *cipher)
Decode a zero terminated C Base64 encoded string.
Definition: base64.c:77
Simple Base64 encoding and decoding functions.
char * buffer
Definition: cJSON.h:167
#define NULL
Definition: rsstats-opts.c:64