#include <stdio.h>
#include <string.h>
#define TXTSIZE 76
char text[TXTSIZE];
char base64[(TXTSIZE - 1) / 3 * 4 + 1];
unsigned char list[173];
char base(char length, char *text, char *base64){
char basecnt = 0;
char textcnt = 0;
char flag = 0;
if(!length)return 0;
if(base64[length - 2] == '\n')base64[length-- - 2] = 0;
while(base64[length - 2] == '='){base64[length - 2] = 0;flag++;}
for(basecnt = 0; basecnt < length; basecnt += 4){
textcnt = basecnt / 4 * 3;
text[textcnt] = ((list[base64[basecnt]] << 2) & 0xfc) |
((list[base64[basecnt + 1]] >> 4) & 0x03);
text[textcnt + 1] = ((list[base64[basecnt + 1]] << 4) & 0xf0) |
((list[base64[basecnt + 2]] >> 2) & 0x0f);
text[textcnt + 2] = ((list[base64[basecnt + 2]] << 6) & 0xc0) |
(list[base64[basecnt + 3]] & 0x3f);
text[textcnt + 3] = '\0';
}
return length / 4 * 3 - flag;
}
int main(int argc, char* argv[]){
char b64 = 'A';
char txt = 0;
for(; b64 <= 'Z'; b64++, txt++)list[b64] = txt;
for(b64 = 'a'; b64 <= 'z'; b64++, txt++)list[b64] = txt;
for(b64 = '0'; b64 <= '9'; b64++, txt++)list[b64] = txt;
list['+'] = txt++;
list['/'] = txt;
FILE *fp = NULL;
if(argc - 1){
fp = fopen(argv[1], "r");
if(!fp){
printf("cannot open the file %s !\n", argv[1]);
return 1;
}
char outf[strlen(argv[1]) - 4 + 1];
sprintf(outf, "%s", argv[1]);
outf[strlen(argv[1]) - 4] = 0;
FILE *fpo = NULL;
fpo = fopen(outf, "wb");
if(!fpo){
printf("cannot write to the file %s !\n", outf);
return 1;
}
memset(base64, 0, (TXTSIZE - 1) / 3 * 4 + 1);
char readcnt = 0;
while(readcnt = base(fread(base64, 1, (TXTSIZE - 1) / 3 * 4 + 1, fp), text, base64)){
fwrite(text, 1, readcnt, fpo);
memset(base64, 0, (TXTSIZE - 1) / 3 * 4 + 1);
}
fclose(fpo);
fclose(fp);
printf("original file has been saved into %s\n", outf);
return 0;
}
else{
memset(base64, 0, (TXTSIZE - 1) / 3 * 4 + 1);
printf("base64 code:");
scanf("%s", base64);
}
base(strlen(base64), text, base64);
printf("original text:%s\n", text);
return 0;
}
用C语言实现base64解密(包括二进制文件)
最新推荐文章于 2024-07-15 13:43:26 发布