1
我一直在玩libcrypto的BIO,我找不到在base64解碼期間檢測錯誤的方法。在libcrypto BIO base64解碼中處理錯誤
即使數據是完整的垃圾,BIO_read
只是返回零,錯誤隊列 - 用ERR_get_error檢查 - 保持空。
與BIO_FLAGS_BASE64_NO_NL
標誌發生同樣的問題:在不匹配的情況下(即數據包含換行符,但設置了標誌;反之亦然),沒有錯誤提示,沒有數據。
那麼,有沒有辦法來解碼錯誤?
static unsigned char *base64_decode(unsigned char *data, size_t len, size_t *out_len)
{
// chain should look like this
// b64 - mem
// so when we read from b64, it gets data from mem and decodes it
BIO *bio_b64;
BIO *bio_mem;
size_t res_capacity;
size_t res_size;
unsigned char *res;
size_t ret;
bio_b64 = BIO_new(BIO_f_base64());
bio_mem = BIO_new_mem_buf(data, len);
res_capacity = 1024;
res_size = 0;
res = malloc(res_capacity);
// don't care about newlines
BIO_set_flags(bio_b64, BIO_FLAGS_BASE64_NO_NL);
BIO_push(bio_b64, bio_mem);
// empty error queue, just in case
while (ERR_get_error() != 0);
while (1) {
ret = BIO_read(bio_b64, &res[res_size], res_capacity - res_size);
if (ret == (res_capacity - res_size)) {
res_size += ret;
res_capacity *= 2;
res = realloc(res, res_capacity);
} else if (ret == 0) {
break;
} else {
res_size += ret;
}
}
if (ERR_get_error() != 0) {
free(res);
return NULL;
}
BIO_free_all(bio_b64);
*out_len = res_size;
return res;
}