C base64编码字符串

标签 c

各位, 尝试解决下面的 base64 函数的问题。通过此过程的请求中大约有 2-3% 返回不正确(太短)的 base64 输出。

static const char *header_request_gce(request_rec *r, char *a)
    {
    char *tim = apr_palloc(r->pool, APR_RFC822_DATE_LEN);
    apr_rfc822_date(tim, r->request_time);

    char *uri = apr_psprintf(r->pool, "%s", r->uri);

    char encode[32768];
    //encode = malloc(strlen(tim)+strlen(uri)); /* make space for the new string (should check the return value ...) */
    strcpy(encode, "GET\n\n\n");
    strcat(encode, tim);
    strcat(encode, "\n");
    strcat(encode, uri);

    unsigned int encode_length = strlen(encode);

    unsigned char* result;
    unsigned char* key = (unsigned char*) "2kcXHh+K+XLtI61/KIV3d1tVzOooTdeOqFii9osz";

    static char res_hexstring[8192];

    result = HMAC(EVP_sha1(), key, 40, encode, encode_length, NULL, NULL);

    char *base64(const unsigned char *input, int length);
    char *base64output = base64(result, strlen(result));

    return base64output;
    }


char *base64(const unsigned char *input, int length)
{
    BIO *bmem, *b64;
    BUF_MEM *bptr;

    b64 = BIO_new(BIO_f_base64());
    bmem = BIO_new(BIO_s_mem());
    b64 = BIO_push(b64, bmem);
    BIO_write(b64, input, length);
    BIO_flush(b64);
    BIO_get_mem_ptr(b64, &bptr);

    char *buff = (char *)malloc(bptr->length);
    memcpy(buff, bptr->data, bptr->length-1);
    buff[bptr->length-1] = 0;

    BIO_free_all(b64);

    return buff;
}

上面的 key 当然已被修改,但保持正确的字符格式

最佳答案

此行不正确:

char *base64output = base64(result, strlen(result));

您正在编码的数据(从 sha1 输出)可以包含 NUL 字节,这意味着 strlen 返回的数字太小(概率为 1 - (255/256 )^20 大约是 7.5%)。您应该将大小作为常量传递,而不是调用 strlen。我相信,如果您只是编码 sha1 哈希值,长度将始终为 20:

char *base64output = base64(result, 20);

可能有更好的方法可以从 HMAC 函数或其他函数中获取该长度(这样,如果您更改哈希算法,它会自动更新),但不可否认,我对您正在使用的哈希函数不太熟悉.

关于C base64编码字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700435/

相关文章:

c - Lua,实现 C API 可访问的线程本地存储

c++ - C 和 C++ 中关键字 static 的含义有何不同?

c - 使用/clr 支持编译的 C++-CLI 库调试 C 程序

c - 表达式语法错误

c - JNI : call to a function where memset happens causes jvm-fetch to crash in the second call

c - 大小信息如何通过指针传递?

c++ - Microsoft Media Foundation 与 Directshow 自定义视频过滤器的等效项是什么?

c - 优化 NEON XOR 实现

iphone - 如何在 NSEnumerator 迭代中获取当前对象的索引?

c - 如何使用C中的直接 header 扫描文件夹中的文本