转自:http://www.cnblogs.com/yejianfei/archive/2013/04/06/3002838.html

  base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于26=64,所以每6位为一个单位,对应某个可打印字符。三个字节共24位,对应于4个base64单位,即3个字节需要用4个可打印字符来表示。它常用来作为电子邮件的传输编码。在base64中的可打印字符包括大写英文字母A-Z,小写英文字母a-z、阿拉伯数字0-9,这样共有62个字符,此外两个可打印符号在不同的系统中而不同,通常用加号(+)和正斜杠(/)。外加“补全符号”,通常用等号(=)。

  完整的base64定义可见RFC 1421和RFC 2045。编码后的数据比原始数据略长,为原来的4/3。在电子邮件中,根据RFC 822的规定,每76个字符,还需要加上回车符和换行符。可以估算编码后数据长度大约为原长的135.1%。

  base64编码的时候,将三个自己的数据,先后放入一个24位的缓冲区中,先来的自己占高位。数据不足3个字节的话,在缓冲区中剩下的位用0补足。然后,每次取出6(因为26=64)位,按照其值选择ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ 中的字符作为编码后的输出。不断进行,直到全部输入数据转换完成。如果最后剩下两个输入数据,在编码结果后加1个“=”;如果最后剩下一个输入数据,编码结果后加2个“=”;如果没有剩下任何数据,就什么都不要加。这样才可以保证资料还原的正确性。

  C语言源代码如下:

/**
* base64编码、解码实现
* C语言源代码
*
* 注意:请使用gcc编译
*
* 叶剑飞
*
*
*
* 使用说明:
* 命令行参数说明:若有“-d”参数,则为base64解码,否则为base64编码。
* 若有“-o”参数,后接文件名,则输出到标准输出文件。
* 输入来自标准输入stdin,输出为标准输出stdout。可重定向输入输出流。
*
* base64编码:输入任意二进制流,读取到文件读完了为止(键盘输入则遇到文件结尾符为止)。
* 输出纯文本的base64编码。
*
* base64解码:输入纯文本的base64编码,读取到文件读完了为止(键盘输入则遇到文件结尾符为止)。
* 输出原来的二进制流。
*
*/ #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <io.h>
#include <fcntl.h>
#include <stdbool.h> #ifndef MAX_PATH
#define MAX_PATH 256
#endif const char * base64char = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char * base64_encode( const unsigned char * bindata, char * base64, int binlength )
{
int i, j;
unsigned char current; for ( i = 0, j = 0 ; i < binlength ; i += 3 )
{
current = (bindata[i] >> 2) ;
current &= (unsigned char)0x3F;
base64[j++] = base64char[(int)current]; current = ( (unsigned char)(bindata[i] << 4 ) ) & ( (unsigned char)0x30 ) ;
if ( i + 1 >= binlength )
{
base64[j++] = base64char[(int)current];
base64[j++] = '=';
base64[j++] = '=';
break;
}
current |= ( (unsigned char)(bindata[i+1] >> 4) ) & ( (unsigned char) 0x0F );
base64[j++] = base64char[(int)current]; current = ( (unsigned char)(bindata[i+1] << 2) ) & ( (unsigned char)0x3C ) ;
if ( i + 2 >= binlength )
{
base64[j++] = base64char[(int)current];
base64[j++] = '=';
break;
}
current |= ( (unsigned char)(bindata[i+2] >> 6) ) & ( (unsigned char) 0x03 );
base64[j++] = base64char[(int)current]; current = ( (unsigned char)bindata[i+2] ) & ( (unsigned char)0x3F ) ;
base64[j++] = base64char[(int)current];
}
base64[j] = '\0';
return base64;
} int base64_decode( const char * base64, unsigned char * bindata )
{
int i, j;
unsigned char k;
unsigned char temp[4];
for ( i = 0, j = 0; base64[i] != '\0' ; i += 4 )
{
memset( temp, 0xFF, sizeof(temp) );
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i] )
temp[0]= k;
}
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i+1] )
temp[1]= k;
}
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i+2] )
temp[2]= k;
}
for ( k = 0 ; k < 64 ; k ++ )
{
if ( base64char[k] == base64[i+3] )
temp[3]= k;
} bindata[j++] = ((unsigned char)(((unsigned char)(temp[0] << 2))&0xFC)) |
((unsigned char)((unsigned char)(temp[1]>>4)&0x03));
if ( base64[i+2] == '=' )
break; bindata[j++] = ((unsigned char)(((unsigned char)(temp[1] << 4))&0xF0)) |
((unsigned char)((unsigned char)(temp[2]>>2)&0x0F));
if ( base64[i+3] == '=' )
break; bindata[j++] = ((unsigned char)(((unsigned char)(temp[2] << 6))&0xF0)) |
((unsigned char)(temp[3]&0x3F));
}
return j;
} void encode(FILE * fp_in, FILE * fp_out)
{
unsigned char bindata[2050];
char base64[4096];
size_t bytes;
while ( !feof( fp_in ) )
{
bytes = fread( bindata, 1, 2049, fp_in );
base64_encode( bindata, base64, bytes );
fprintf( fp_out, "%s", base64 );
}
} void decode(FILE * fp_in, FILE * fp_out)
{
int i;
unsigned char bindata[2050];
char base64[4096];
size_t bytes;
while ( !feof( fp_in ) )
{
for ( i = 0 ; i < 2048 ; i ++ )
{
base64[i] = fgetc(fp_in);
if ( base64[i] == EOF )
break;
else if ( base64[i] == '\n' || base64[i] == '\r' )
i --;
}
bytes = base64_decode( base64, bindata );
fwrite( bindata, bytes, 1, fp_out );
}
} void help(const char * filepath)
{
fprintf( stderr, "Usage: %s [-d] [input_filename] [-o output_filepath]\n", filepath );
fprintf( stderr, "\t-d\tdecode data\n" );
fprintf( stderr, "\t-o\toutput filepath\n\n" );
} int main(int argc, char * argv[])
{
FILE * fp_input = NULL;
FILE * fp_output = NULL;
bool isencode = true;
bool needHelp = false;
int opt = 0;
char input_filename[MAX_PATH] = "";
char output_filename[MAX_PATH] = ""; opterr = 0;
while ( (opt = getopt(argc, argv, "hdo:")) != -1 )
{
switch(opt)
{
case 'd':
isencode = false;
break;
case 'o':
strncpy(output_filename, optarg, sizeof(output_filename));
output_filename[sizeof(output_filename)-1] = '\0';
break;
case 'h':
needHelp = true;
break;
default:
fprintf(stderr, "%s: invalid option -- %c\n", argv[0], optopt);
needHelp = true;
break;
}
}
if ( optind < argc )
{
strncpy(input_filename, argv[optind], sizeof(input_filename));
input_filename[sizeof(input_filename)-1] = '\0';
} if (needHelp)
{
help(argv[0]);
return EXIT_FAILURE;
} if ( !strcmp(input_filename, "") )
{
fp_input = stdin;
if (isencode)
_setmode( _fileno(stdin), _O_BINARY );
}
else
{
if (isencode)
fp_input = fopen(input_filename, "rb");
else
fp_input = fopen(input_filename, "r");
}
if ( fp_input == NULL )
{
fprintf(stderr, "Input file open error\n");
return EXIT_FAILURE;
} if ( !strcmp(output_filename, "") )
{
fp_output = stdout;
if (!isencode)
_setmode( _fileno(stdout), _O_BINARY );
}
else
{
if (isencode)
fp_output = fopen(output_filename, "w");
else
fp_output = fopen(output_filename, "wb");
}
if ( fp_output == NULL )
{
fclose(fp_input);
fp_input = NULL;
fprintf(stderr, "Output file open error\n");
return EXIT_FAILURE;
} if (isencode)
encode(fp_input, fp_output);
else
decode(fp_input, fp_output);
fclose(fp_input);
fclose(fp_output);
fp_input = fp_output = NULL;
return EXIT_SUCCESS;
}

最新文章

  1. mybatis- spring 批量实现数据导入数据库
  2. 2014ACM/ICPC亚洲区北京站
  3. IOS设计模式浅析之工厂方法模式(Factory Method)
  4. Pinyin4Net
  5. Chrome 开发者工具有了设备模拟器
  6. win7引导项顺序
  7. 【产品体验】eyepetizer开眼
  8. hdu 4758 Walk Through Squares
  9. java学习笔记 --- 异常
  10. Installing MySQL on Microsoft Windows Using a noinstall Zip Archive
  11. JavaEE成长之路
  12. SVN上传文件自动更新到发布站点
  13. DbContext 和 ObjectContext两者的区别
  14. Codeforces Beta Round #77 (Div. 2 Only)
  15. WCF分布式开发常见错误解决(1):An error occurred while attempting to find services at...添加服务引用出错
  16. c++时间计算模块
  17. [hihoCoder] 第五十二周: 连通性&#183;一
  18. 20172333 2017-2018-2 《Java程序设计》第10周学习总结
  19. INFO hdfs.DFSClient: Exception in createBlockOutputStream java.net解决办法
  20. Java 自定义异常类

热门文章

  1. Oauth 2.0第三方账号登录原理图
  2. JSONP跨域的原理解析
  3. Linux安装字体
  4. http get vs post
  5. UVALive 4953 Wormly--【提醒自己看题要仔细】
  6. SuSE Linux 开启VNC服务
  7. C# Arraylist + struct 综合练习 枚举ENUE 递归
  8. iOS-JavaScript向WKWebView传值
  9. 25个增强iOS应用程序性能的提示和技巧(高级篇)(1)
  10. XMPP框架下微信项目总结(7)聊天通信处理-发送,接受数据