#include
#include
#include
const char BASE64_CHAR[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
//编码
char *base64_encode(const unsigned char *src, size_t len) {
char *out = NULL;
size_t i, j;
const unsigned char *p = src;
out = (char *) malloc(len * 4 / 3 + 4);
if (out == NULL) {
return NULL;
}
for (i = 0, j = 0; i < len; i += 3, j += 4) {
unsigned int val = p[i] << 16 | (i + 1 < len ? p[i + 1] << 8 : 0) | (i + 2 < len ? p[i + 2] : 0);
out[j + 0] = BASE64_CHAR[(val >> 18) & 0x3F];
out[j + 1] = BASE64_CHAR[(val >> 12) & 0x3F];
out[j + 2] = (i + 1 < len) ? BASE64_CHAR[(val >> 6) & 0x3F] : '=';
out[j + 3] = (i + 2 < len) ? BASE64_CHAR[(val >> 0) & 0x3F] : '=';
}
out[j] = '\0';
return out;
}
//解码
int base64_decode(const char* encoded_data, char* decoded_data) {
int i, j, k = 0;
int padding = 0;
int len = strlen(encoded_data);
if (len < 4) {
return 0;
}
if (encoded_data[len - 1] == '=') {
padding++;
}
if (encoded_data[len - 2] == '=') {
padding++;
}
int decoded_len = 3 * len / 4 - padding;
for (i = 0; i < len; i += 4) {
int c[4];
for (j = 0; j < 4; j++) {
c[j] = strchr(BASE64_CHAR, encoded_data[i + j]) - BASE64_CHAR;
}
decoded_data[k++] = (char)((c[0] << 2) | (c[1] >> 4));
if (k >= decoded_len) {
break;
}
decoded_data[k++] = (char)(((c[1] & 0x0f) << 4) | (c[2] >> 2));
if (k >= decoded_len) {
break;
}
decoded_data[k++] = (char)(((c[2] & 0x03) << 6) | c[3]);
}
return decoded_len;
}
测试
int main() {
char *src = "12w3454353rwrewrewdc法国德国的风格";
char *encode = base64_encode((const unsigned char *) src, strlen(src));
printf("base64 encode:%s\n", encode);
char decoded[128];
int decoded_len = base64_decode(encode, decoded);
decoded[decoded_len] = '\0';
printf("base64 decode:%s\n", decoded);
free(encode);
return 0;
}
结果
g++ base.cpp
base.cpp: In function 'int main()':
base.cpp:66:17: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
char *src = "12w3454353rwrewrewdc法国德国的风格";
^
a
base64 encode:MTJ3MzQ1NDM1M3J3cmV3cmV3ZGO3qLn6tcK5+rXEt+e48Q==
base64 decode:12w3454353rwrewrewdc法国德国的风格