Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- static int decode_matrix[128] =
- { -1,-1,-1,-1,-1,-1,-1,-1 // A..Z = 0..25
- , -1,-1,-1,-1,-1,-1,-1,-1 // a..z = 26..51
- , -1,-1,-1,-1,-1,-1,-1,-1 // 0..9 = 52..61
- , -1,-1,-1,-1,-1,-1,-1,-1 // +,/ = 62,63
- , -1,-1,-1,-1,-1,-1,-1,-1
- , -1,-1,-1,62,-1,-1,-1,63
- , 52,53,54,55,56,57,58,59
- , 60,61,-1,-1,-1,-1,-1,-1
- , -1, 0, 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,-1,-1,-1,-1,-1
- , -1,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,-1,-1,-1,-1,-1 };
- static int decode_base64_char (char c)
- {
- if ((unsigned char) c < 128) {
- return decode_matrix[c];
- } else {
- return -1;
- }
- }
- static char* write_64 (int data, char* out, int* bit_pos)
- {
- switch (*bit_pos) {
- case 6: // ======xx xxxx----
- *out &= 0xfc;
- *out |= data >> 4;
- *(out + 1) = data << 4;
- *bit_pos = 4;
- return out + 1;
- case 4: // ====xxxx xx------
- *out &= 0xf0;
- *out |= data >> 2;
- *(out + 1) = data << 6;
- *bit_pos = 2;
- return out + 1;
- case 2: // ==xxxxxx --------
- *out &= 0xc0;
- *out |= data;
- *bit_pos = 0;
- return out + 1;
- case 0: // xxxxxx-- --------
- *out = data << 2;
- *bit_pos = 6;
- return out;
- default: return out;
- }
- }
- static char* finish_64 (char* out, int bit_pos)
- {
- switch (bit_pos) {
- case 6: // ======00
- *out &= 0xfc;
- return out + 1;
- break;
- case 4: // ====0000
- *out &= 0xf0;
- return out + 1;
- break;
- case 2: // ==000000
- *out &= 0xc0;
- return out + 1;
- break;
- case 0: // --------
- default:
- return out;
- }
- }
- char* decode_base64 (char* output, const char* input)
- {
- int decoded;
- int bit_pos = 0;
- for (;;) {
- if (*input == '=' || *input == '\0') {
- break;
- }
- decoded = decode_base64_char(*input++);
- if (decoded == -1) {
- return NULL;
- }
- output = write_64(decoded, output, &bit_pos);
- }
- output = finish_64(output, bit_pos);
- *output = '\0';
- return output;
- }
- int main (int argc, char** argv)
- {
- char* input;
- char* output;
- if (argc > 1) {
- input = argv[1];
- } else {
- input = "aGVsbG8sIHdvcmxkIQ==";
- }
- output = malloc(strlen(input) / 8 * 6 + 2);
- if (decode_base64(output, input)) {
- printf("%s\n", output);
- } else {
- printf("invalid base64\n");
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement