/*----------------------------------------------------*/ /* b64decode.c -- Base64-Decoding Filter */ /*----------------------------------------------------*/ /* Usage: */ /* b64decode [infile] > */ /* infile: filename of the file to be decoded */ /* (if omitted, input from stdin) */ /* result(stdout) should be redirected to */ /*----------------------------------------------------*/ #include #include #include int main(int argc, char *argv[]) { int c, m, c1, c2, k=0; FILE *fp; # ifdef O_BINARY setmode(1,O_BINARY); # endif if (argc == 1) { fp = stdin; # ifdef O_BINARY setmode(0,O_BINARY); # endif } else if ((fp=fopen(argv[1],"rb")) == NULL) { fprintf(stderr, "file %s not found\n", argv[1]); exit(1); } while ((c=getc(fp)) != EOF) { if ((c=='\n') || (c=='\r')) continue; else if ((c>=0x41) && (c<=0x5A)) m = c-0x41; /* 'A'-'Z': 0-25 */ else if ((c>=0x61) && (c<=0x7A)) m = c-0x61 + 26; /* 'a'-'z': 26-51 */ else if ((c>=0x30) && (c<=0x39)) m = c-0x30 + 52; /* '0'-'9': 52-61 */ else if (c == '+') m = 62; else if (c == '/') m = 63; else if (c == '=') { if (k == 0) { fprintf(stderr, "\n*** unexpected '=' char neglected\n"); continue; } if (c1 != 0) { fprintf(stderr, "\n*** illegal padding('='), partial data lost\n"); } c1 = 0; if (++k > 3) k = 0; continue; } else { fprintf(stderr, "\n*** illegal Base64 char '%c' neglected\n", c); continue; } if (k == 0) { c1 = (m & 0x3F) << 2; k++; } else if (k == 1) { c2 = (m & 0x30) >> 4; putchar(c1|c2); c1 = (m & 0x0F) << 4; k++; } else if (k == 2) { c2 = (m & 0x3C) >> 2; putchar(c1|c2); c1 = (m & 0x03) << 6; k++; } else if (k == 3) { c2 = (m & 0x3F); putchar(c1|c2); c1 = 0; k = 0; } } if (k != 0) fprintf(stderr, "\n*** incomplete trailing char\n"); fclose(fp); fclose(stdout); return(0); }