概述
#include<stdio.h>
const char *BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//3*8=4*6 将3个字节每6位拆分成4个字节,由于拆分后的每个字节只有6位,所以值为0到63,再将对应的值转成上面对应的字符就可以了
void _base64_encode_triple(unsigned char triple[3], char result[4])
{
int tripleValue, i;
tripleValue = triple[0];
tripleValue *= 256;
tripleValue += triple[1];
tripleValue *= 256;
tripleValue += triple[2];//3个字节的值大小
for (i=0; i<4; i++)
{
result[3-i] = BASE64_CHARS[tripleValue%64];//tripleValue%64 为取最后6位的值
tripleValue /= 64;//去掉最后6位的值
}
}
/**
* encode an array of bytes using Base64 (RFC 3548)
*
* @param source the source buffer
* @param sourcelen the length of the source buffer
* @param target the target buffer
* @param targetlen the length of the target buffer
* @return 1 on success, 0 otherwise
*/
int base64_encode(unsigned char *source, unsigned int sourcelen, char *target, unsigned int targetlen)
{
/* check if the result will fit in the target buffer */
if ((sourcelen+2)/3*4 > targetlen-1)
return 0;
/* encode all full triples */
while (sourcelen >= 3)
{
_base64_encode_triple(source, target);//每次转3个字节
sourcelen -= 3;
source += 3;
target += 4;
}
/* encode the last one or two characters */
if (sourcelen > 0)//剩下少于3个字节的最后一次做特殊处理
{
unsigned char temp[3];
memset(temp, 0, sizeof(temp));
memcpy(temp, source, sourcelen);
_base64_encode_triple(temp, target);
target[3] = '=';
if (sourcelen == 1)
target[2] = '=';
target += 4;
}
/* terminate the string */
target[0] = 0;
return 1;
}
/**
* decode a base64 string and put the result in the same buffer as the source
*
* This function does not handle decoded data that contains the null byte
* very well as the size of the decoded data is not returned.
*
* The result will be zero terminated.
*
* @deprecated use base64_decode instead
*
* @param str buffer for the source and the result
*/
void str_b64decode(char* str)
{
size_t decoded_length;
decoded_length = base64_decode(str, (unsigned char *)str, strlen(str));
str[decoded_length] = '