c语言base64加解密
时间: 2023-11-02 10:07:38 浏览: 121
C语言中没有内置的Base64加解密函数,但可以通过调用第三方库来实现。
一个常用的第三方库是openssl,使用它可以很方便地进行Base64编码和解码。
以下是一个示例程序,展示了如何使用openssl库进行Base64编码和解码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
int base64_encode(const char *input, int input_len, char *output, int output_size)
{
BIO *bmem = NULL;
BIO *b64 = NULL;
BUF_MEM *bptr = NULL;
b64 = BIO_new(BIO_f_base64());
if (b64 == NULL) {
return -1;
}
bmem = BIO_new(BIO_s_mem());
if (bmem == NULL) {
BIO_free(b64);
return -1;
}
b64 = BIO_push(b64, bmem);
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
if (BIO_write(b64, input, input_len) <= 0) {
BIO_free_all(b64);
return -1;
}
if (BIO_flush(b64) <= 0) {
BIO_free_all(b64);
return -1;
}
BIO_get_mem_ptr(b64, &bptr);
if (bptr->length > output_size) {
BIO_free_all(b64);
return -1;
}
memcpy(output, bptr->data, bptr->length);
output[bptr->length] = '\0';
BIO_free_all(b64);
return bptr->length;
}
int base64_decode(const char *input, int input_len, char *output, int output_size)
{
BIO *bmem = NULL;
BIO *b64 = NULL;
b64 = BIO_new(BIO_f_base64());
if (b64 == NULL) {
return -1;
}
bmem = BIO_new_mem_buf((void *)input, input_len);
if (bmem == NULL) {
BIO_free(b64);
return -1;
}
bmem = BIO_push(b64, bmem);
int len = BIO_read(bmem, output, output_size);
if (len < 0) {
BIO_free_all(bmem);
return -1;
}
output[len] = '\0';
BIO_free_all(bmem);
return len;
}
int main()
{
char input[] = "hello world";
char encoded[100];
char decoded[100];
printf("Original: %s\n", input);
int len = base64_encode(input, strlen(input), encoded, sizeof(encoded));
printf("Encoded: %s (%d)\n", encoded, len);
len = base64_decode(encoded, len, decoded, sizeof(decoded));
printf("Decoded: %s (%d)\n", decoded, len);
return 0;
}
```
运行结果如下:
```
Original: hello world
Encoded: aGVsbG8gd29ybGQ= (16)
Decoded: hello world (11)
```
阅读全文