民间, 尝试解决下面的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;
}
上面的密钥已被修改为课程,但保持正确的字符格式
答案 0 :(得分:5)
此行不正确:
char *base64output = base64(result, strlen(result));
您编码的数据(来自sha1的输出)可以包含NUL
字节,这意味着strlen返回的数字太小(概率为1 - (255/256)^20
,大约为{{1} })。而不是调用7.5%
,你应该将大小作为常量传递。我相信如果你只是编码一个sha1哈希,长度总是20:
strlen
有一种更好的方法可以从HMAC函数中获取该长度(如果更改散列算法,它会自动更新),但我确实不熟悉您正在使用的散列函数