-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathbase64.c
74 lines (60 loc) · 2.48 KB
/
base64.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/***********************************************************
* Base64 library implementation *
* @author Ahmed Elzoughby *
* @date July 23, 2017 *
***********************************************************/
#include "base64.h"
char base46_map[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
char* base64_encode(char* plain) {
char counts = 0;
char buffer[3];
char* cipher = malloc(strlen(plain) * 4 / 3 + 4);
int i = 0, c = 0;
for(i = 0; plain[i] != '\0'; i++) {
buffer[counts++] = plain[i];
if(counts == 3) {
cipher[c++] = base46_map[buffer[0] >> 2];
cipher[c++] = base46_map[((buffer[0] & 0x03) << 4) + (buffer[1] >> 4)];
cipher[c++] = base46_map[((buffer[1] & 0x0f) << 2) + (buffer[2] >> 6)];
cipher[c++] = base46_map[buffer[2] & 0x3f];
counts = 0;
}
}
if(counts > 0) {
cipher[c++] = base46_map[buffer[0] >> 2];
if(counts == 1) {
cipher[c++] = base46_map[(buffer[0] & 0x03) << 4];
cipher[c++] = '=';
} else { // if counts == 2
cipher[c++] = base46_map[((buffer[0] & 0x03) << 4) + (buffer[1] >> 4)];
cipher[c++] = base46_map[(buffer[1] & 0x0f) << 2];
}
cipher[c++] = '=';
}
cipher[c] = '\0'; /* string padding character */
return cipher;
}
char* base64_decode(char* cipher) {
char counts = 0;
char buffer[4];
char* plain = malloc(strlen(cipher) * 3 / 4);
int i = 0, p = 0;
for(i = 0; cipher[i] != '\0'; i++) {
char k;
for(k = 0 ; k < 64 && base46_map[k] != cipher[i]; k++);
buffer[counts++] = k;
if(counts == 4) {
plain[p++] = (buffer[0] << 2) + (buffer[1] >> 4);
if(buffer[2] != 64)
plain[p++] = (buffer[1] << 4) + (buffer[2] >> 2);
if(buffer[3] != 64)
plain[p++] = (buffer[2] << 6) + buffer[3];
counts = 0;
}
}
plain[p] = '\0'; /* string padding character */
return plain;
}