/* This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://www.wtfpl.net/ for more details. */ #include #include #include #ifdef _WIN32 # include # include #endif const char BASE64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /* put 4 chars, maintain col width */ void put4(int src[4], int colwidth) { static int col = 0; int i; for(i = 0; i < 4; ++i) { putchar(src[i]); ++col; if(colwidth > 0 && col == colwidth) { putchar('\n'); col = 0; } } } /* read binary and write base64 */ void encode(int colwidth) { int w[4], r[3]; #ifdef _WIN32 _setmode(STDIN_FILENO, _O_BINARY); #endif for(; ; ) { if((r[0] = getchar()) == EOF) { return; } w[0] = BASE64[r[0] >> 2]; w[1] = BASE64[(r[0] & 3) << 4]; w[2] = '='; w[3] = '='; if((r[1] = getchar()) == EOF) { put4(w, colwidth); return; } w[1] = BASE64[((r[0] & 3) << 4) | (r[1] >> 4)]; w[2] = BASE64[(r[1] & 15) << 2]; if((r[2] = getchar()) == EOF) { put4(w, colwidth); return; } w[2] = BASE64[((r[1] & 15) << 2) | (r[2] >> 6)]; w[3] = BASE64[r[2] & 63]; put4(w, colwidth); } } /* read base64 and write binary */ void decode(void) { int c, r[4], i; char *p; #ifdef _WIN32 _setmode(STDOUT_FILENO, _O_BINARY); #endif for(; ; ) { for(i = 0; i < 4 && (c = getchar()) != EOF; ) { if((p = strchr(BASE64, c)) != NULL) r[i++] = p - BASE64; } if(i == 0 || i == 1) return; /* ==== or x=== (actually invalid) */ putchar((r[0] << 2) | (r[1] >> 4)); if(i == 2) return; /* xx== */ putchar(((r[1] & 15) << 4) | (r[2] >> 2)); if(i == 3) return; /* xxx= */ putchar((r[2] << 6) | r[3]); } } int main(int argc, char *argv[]) { int i, ncol = 76, mode = 0; for(i = 1; i < argc; ++i) { if(!strncmp(argv[i], "-w=", 3)) ncol = atoi(&argv[i][3]); else if(!strncmp(argv[i], "--wrap=", 7)) ncol = atoi(&argv[i][7]); else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--decode")) mode = 1; else if(!strcmp(argv[i], "--help")) { printf("Usage: %s [--help] [-d | --decode] [-w | --" "wrap=COLS]\nInvalid commands are ignored.\nRead fr" "om stdin, write to stdout.\nIf COLS is 0 or not a " "valid number, no wrapping is performed. Default to" " 76.\n", argv[0]); return 0; } } if(mode) decode(); else encode(ncol); return 0; }