本文写给需要用到base64编解码的朋友们,可以作为工具文章,在需要时查阅。
关于什么是base64编解码,度娘比我解释的更清楚。这里只说一下,在一些二进制数据或不可见字符操作不便的情况下(例如http请求参数等),可将这类二进制数据通过base64编码转换为可见字符。当然有编码自然也有对等的解码恢复原始数据。
闲话少叙,代码奉上:
/** Author: 码哥比特*/
#include <stdio.h>
#include <stdlib.h>static char baseMap[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";int base64_encode(unsigned char *in, size_t inlen, unsigned char **out, size_t *outlen)
{size_t i, state, j;*outlen = inlen / 3 * 4;if (inlen % 3) (*outlen) += 4;*out = (unsigned char *)calloc(1, *outlen + 1);if (*out == NULL) return -1;unsigned char *o = *out;for (i = 0, state = 0, j = 0; i < inlen; ++j) {if (state == 0) {o[j] = (unsigned char)baseMap[(in[i] >> 2) & 0x3f];state = 1;} else if (state == 1) {if (i+1 >= inlen) {o[j++] = (unsigned char)baseMap[(in[i] & 0x3) << 4];o[j++] = (unsigned char)'=';o[j] = (unsigned char)'=';break;} else {o[j] = (unsigned char)baseMap[((in[i] & 0x3) << 4)|((in[i+1] >> 4) & 0xf)];++i;state = 2;}} else {if (i+1 >= inlen) {o[j++] = (unsigned char)baseMap[((in[i] & 0xf) << 2)];o[j] = (unsigned char)'=';break;} else {o[j++] = (unsigned char)baseMap[((in[i] & 0xf) << 2)|((in[i+1] >> 6) & 0x3)];o[j] = (unsigned char)baseMap[in[++i] & 0x3f];++i;state = 0;}}}return 0;
}int base64_decode(unsigned char *in, size_t inlen, unsigned char **out, size_t *outlen)
{if (inlen % 4) return -1;unsigned char ascii[256] = {0};size_t i, state, j;for (i = 0; i < 64; ++i) {ascii[(unsigned char)baseMap[i]] = i;}*outlen = inlen / 4 * 3;if (in[inlen-1] == '=') --(*outlen);if (in[inlen-2] == '=') --(*outlen);*out = (unsigned char *)calloc(1, *outlen + 1);if (*out == NULL) return -1;unsigned char *o = *out;for (i = 0, state = 0, j = 0; i < inlen; ) {if (state == 0) {o[j] = (ascii[in[i]] << 2);state = 1;++i;} else if (state == 1) {o[j++] |= ((ascii[in[i]] >> 4) & 0x3);state = 2;} else if (state == 2) {o[j] = (ascii[in[i]] & 0xf) << 4;state = 3;++i;} else if (state == 3) {if (in[i] == '=') break;o[j++] |= ((ascii[in[i]] >> 2) & 0xf);state = 4;} else if (state == 4) {o[j] = (ascii[in[i]] & 0x3) << 6;state = 5;++i;} else {if (in[i] == '=') break;o[j++] |= (ascii[in[i]] & 0x3f);state = 0;++i;}}return 0;
}void base64_free(unsigned char *data)
{if (data == NULL) return;free(data);
}
encode
/decode
函数的参数1、2为输入内容,参数3、4为编解码的结果部分。
如果编解码成功返回值为0,否则返回值为-1。
编解码成功时,参数三将返回一个动态分配的内存空间,因此封装了一个base64_free
函数用来释放该部分内存。读者使用时,也可以根据需要将分配和释放内存的方式进行修改。