最近工作中遇到base64编解码,所以深入了解了下。
c语言和java的处理逻辑是不一样的,Linux下c语言实现主要有两种:
1.通用的base64编码和解码,即不依赖其他库的实现,不过这种方法,工作中目前测试不太适用。
2.依赖openssl库实现编码和解码
代码如下:
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h> // Add this header for BUF_MEM definition
#include <string.h>
#include <stdio.h>
#include <stdlib.h> // Include stdlib.h for malloc/free
int base64_encode(const unsigned char *input, int length, char **encoded_data) {
BIO *bio, *b64;
BUF_MEM *buffer_ptr;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio, input, length);
BIO_flush(bio);
BIO_get_mem_ptr(bio, &buffer_ptr);
*encoded_data = (char *)malloc(buffer_ptr->length + 1);
memcpy(*encoded_data, buffer_ptr->data, buffer_ptr->length);
(*encoded_data)[buffer_ptr->length] = '\0';
BIO_free_all(bio);
return 0;
}
int base64_decode(const char *input, unsigned char **decoded_data, int *decoded_length) {
BIO *bio, *b64;
int decode_len = 0;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new_mem_buf((void*)input, -1); // Cast input to void* to match function signature
bio = BIO_push(b64, bio);
BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL);
*decoded_data = (unsigned char *)malloc(strlen(input));
decode_len = BIO_read(bio, *decoded_data, strlen(input));
BIO_free_all(bio);
*decoded_length = decode_len;
return (decode_len > 0);
}
int main() {
const char *original_data = "Hello, OpenSSL!";
char *encoded_data;
unsigned char *decoded_data;
int decoded_length;
// Base64 Encode
base64_encode((const unsigned char *)original_data, strlen(original_data), &encoded_data);
printf("Base64 Encoded: %s\n", encoded_data);
// Base64 Decode
base64_decode(encoded_data, &decoded_data, &decoded_length);
decoded_data[decoded_length] = '\0';
printf("Base64 Decoded: %s\n", decoded_data);
// Free allocated memory
free(encoded_data);
free(decoded_data);
return 0;
}
openssl一般系统自带,直接用,编译命令如下:
g++ -o test test.cpp -lssl -lcrypto
执行结果如下:
./test
Base64 Encoded: SGVsbG8sIE9wZW5TU0wh
Base64 Decoded: Hello, OpenSSL!
如果直接用命令行执行
-
命令行工具使用示例:
-
编码:
echo -n "Hello, World!" | openssl enc -base64
输出:
SGVsbG8sIFdvcmxkIQ==
-
解码:
cho -n "SGVsbG8sIFdvcmxkIQ==" | openssl enc -d -base64
输出:
Hello, World!
-