C语言实现base64编解码
2023-12-30 09:30:23
本文写给需要用到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
函数用来释放该部分内存。读者使用时,也可以根据需要将分配和释放内存的方式进行修改。
文章来源:https://blog.csdn.net/weixin_40960130/article/details/135300351
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!