我正在尝试通过使用此处提到的实现来获取字符串值“简单”的 Base 64 编码值
#include<openssl/sha.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdint.h>
#include<stdlib.h>
static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
static int mod_table[] = {0,2,1};
char *base64_encode(const unsigned char *data,
size_t input_length,
size_t *output_length)
{
printf("-- Begins -- ");
*output_length = (size_t) (4.0 * ceil((double) input_length / 3.0));
char *encoded_data = malloc(*output_length);
for (int i = 0, j = 0; i < input_length;) {
uint32_t octet_a = i < input_length ? data[i++] : 0;
uint32_t octet_b = i < input_length ? data[i++] : 0;
uint32_t octet_c = i < input_length ? data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F];
encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F];
}
for (int i = 0; i < mod_table[input_length % 3]; i++)
encoded_data[*output_length - 1 - i] = '=';
printf(" -- Ends -- ");
return encoded_data;
}
int main(int argc, char **argv)
{
unsigned char ibuf[] = "simple";
size_t *outLen;
size_t *inLen = (size_t) strlen(ibuf);
char *encodeVal = base64_encode(ibuf, inLen, outLen);
return(0);
}
当我尝试使用 gdb 进行调试时,我得到的只是:
Program received signal SIGSEGV, Segmentation fault.
0x000000000040073f in base64_encode (data=0x7fff65298a90 "simple", input_length=6, output_length=0x400a50) at openSha.c:25
25 *output_length = (size_t) (4.0 * ceil((double) input_length / 3.0));
这里有什么错误?我很久没有用 C 编码了,所以如果我在这里遗漏了一些明显的东西,我很抱歉。