about summary refs log tree commit diff stats
path: root/b64f.c
blob: aa17963dfeccbc1835e65eb11444528e00dbf8f3 (plain) (blame)
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
75
76
77
78
79
80
#include <u.h>
#include <libc.h>
#include <stdio.h>

#include "base64.h"

int lower(int a);

void main(int argc,char** argv) {
	
	char opt = ' ';
	if (argc > 1)
		opt = lower(argv[1][0]);
	
	if ( ((argc < 4) && (opt!='b' && opt!='t')) ) {
		puts("\nbase64.c [Encode/Decode]");
		puts("------------------------------------");
		printf("File mode\n");
		printf("\tUse the following to encode:\n\t%s e(ncode) IN_filepath OUT_filepath\n",argv[0]);
		printf("\tUse the following to decode:\n\t%s d(ecode) IN_filepath OUT_filepath\n",argv[0]);
		printf("\nText mode (outputs to stdout):\n");
		printf("\tUse the following to encode:\n\t%s t(ext) IN_Text\n",argv[0]);
		printf("\tUse the following to decode:\n\t%s b(ase64) IN_Base64\n",argv[0]);
		
		puts("\nERROR: insufficient or incorrect parameters...");
		exits("1");
	}
	
	int bcoded = 0;
	switch(opt) {
		case 'd':
			puts("\nDECODING");
			bcoded = b64_decode(argv[2],argv[3]);
			break;
		case 'e':
			puts("\nENCODING");
			bcoded = b64_encodef(argv[2],argv[3]);
			break;
		case 't':
			puts("\nENCODING from text to base64");
			
				int tlen = strlen(argv[2]);
				char *b64 = (char *)malloc(1 + (sizeof(char) * b64e_size(tlen)));
				if (b64 == NULL) {
					printf("Error: cannot allocate memory for output\n");
					exits("1");  /* End program with error status. */
				}
			
			bcoded = b64_encode(argv[2],tlen,b64);
			printf("Encoded base64 from text: %s", b64);
			free(b64);
			break;
		case 'b':
			puts("\nDECODING from base64 to text");
			
				int blen = strlen(argv[2]);
				char *txt = malloc(1 + (sizeof(char) * b64d_size(blen)));
				if (txt == NULL) {
					printf("Error: cannot allocate memory for output\n");
					exits("1");  /* End program with error status. */
				}
			
			//bcoded = b64_decode(argv[2],blen,txt);
			txt[bcoded] = '\0';
			printf("Decoded text from base64: %s", txt);
			free(txt);
			break;
		default:
			puts("\nINVALID OPTION");
			bcoded = -1;
	}
	
	printf("\nBytes encoded/decoded: %i\n",bcoded);
}

int lower(int a) { //https://stackoverflow.com/a/15709023/883015
    if ((a >= 0x41) && (a <= 0x5A))
        a |= 0x20; 
    return a;  
}