c# - 使用 C 和 OpenSSL 进行 Base64 编码

标签 c# c openssl base64

我正在尝试在 C 中使用 base64 和 OpenSSL 对字符串进行编码,然后在 C# 中对其进行解码。我有以下编码代码:

char *base64(const 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_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    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;
}

问题是,当我在 C# 中对其进行解码时,出现以下错误:

Invalid length for a Base-64 char array or string.

搜索后,我发现解码后的字符串长度无效,于是我开始尝试编码后的字符串,发现(在我看来)OpenSSL 库没有将换行符\n 加密为单个换行符,但是作为两个独立的符号。我是不是编码错了,对换行符的想法有误,还是有可能是其他任何东西?不要以为还需要另一个代码片段,所以这是我粘贴的唯一一个代码片段,但如果需要,我会提供另一个代码片段。

最佳答案

问题在

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

因为,它比 Base64 少了一个字节。

应该是

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

这应该有效。

关于c# - 使用 C 和 OpenSSL 进行 Base64 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22861325/

相关文章:

c# - LINQ-to-XML 到 DataGridView : Cannot edit fields -- How to fix?

c# - Azure 媒体服务从 HTML 上传

C# 不需要重复类实例化吗?

c# - IIS session 在发布 Web 上丢失

python - CPython 解释器如何处理 OOP

c - 来自/lib/x86_64-linux-gnu/libcrypto.so.1.0.0 的段错误

c - C 中的 SSL 包装器流

java - 为什么我的 Java 私钥签名与 Openssl 签名不匹配?

c - 将文本读入C中的链表

linux -/usr/local/ssl/lib/libcrypto.a : could not read symbols: Bad value