c语言实现base64编码解码
时间: 2023-09-07 11:16:30 浏览: 160
以下是C语言实现Base64编码和解码的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char base64_chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int is_base64(char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
char *base64_encode(const unsigned char *data, size_t input_length, size_t *output_length) {
*output_length = 4 * ((input_length + 2) / 3);
char *encoded_data = malloc(*output_length + 1);
if (encoded_data == NULL) return NULL;
int i, j;
for (i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_b = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t octet_c = i < input_length ? (unsigned char)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = base64_chars[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = base64_chars[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = base64_chars[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = base64_chars[(triple >> 0 * 6) & 0x3F];
}
while ((*output_length) > 0 && encoded_data[*output_length - 1] == '=') (*output_length)--;
encoded_data[*output_length] = '\0';
return encoded_data;
}
unsigned char *base64_decode(const char *data, size_t input_length, size_t *output_length) {
if (input_length % 4 != 0) return NULL;
*output_length = input_length / 4 * 3;
if (data[input_length - 1] == '=') (*output_length)--;
if (data[input_length - 2] == '=') (*output_length)--;
unsigned char *decoded_data = malloc(*output_length + 1);
if (decoded_data == NULL) return NULL;
int i, j;
for (i = 0, j = 0; i < input_length;) {
uint32_t sextet_a = data[i] == '=' ? 0 & i++ : base64_chars[(unsigned char)data[i++]];
uint32_t sextet_b = data[i] == '=' ? 0 & i++ : base64_chars[(unsigned char)data[i++]];
uint32_t sextet_c = data[i] == '=' ? 0 & i++ : base64_chars[(unsigned char)data[i++]];
uint32_t sextet_d = data[i] == '=' ? 0 & i++ : base64_chars[(unsigned char)data[i++]];
uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);
if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
}
decoded_data[*output_length] = '\0';
return decoded_data;
}
```
使用示例:
```c
int main() {
const char *message = "Hello, world!";
size_t input_length = strlen(message);
size_t output_length = 0;
char *encoded_data = base64_encode((const unsigned char *)message, input_length, &output_length);
printf("Base64 encoded: %s\n", encoded_data);
unsigned char *decoded_data = base64_decode(encoded_data, output_length, &input_length);
printf("Base64 decoded: %s\n", (const char *)decoded_data);
free(encoded_data);
free(decoded_data);
return 0;
}
```
输出:
```
Base64 encoded: SGVsbG8sIHdvcmxkIQ==
Base64 decoded: Hello, world!
```
阅读全文