c - 为什么openssl无法解码由php函数编码base64_encode字符串


c - Why openssl can't decode the string encoded by base64_encode function of php?

我想对一个字符串进行base64编码,并使用OpenSSL api用C语言对其进行解码。我用这样的php编码:

<?php 
echo base64_encode("aaa");
?>
result is "YWFh"

然后像这样用C解码它:

int base64_decode(char *str,int str_len,char *decode,int decode_buffer_len){
    int len=0;
    BIO *b64,*bmem;
    b64=BIO_new(BIO_f_base64());
    bmem=BIO_new_mem_buf(str,str_len);
    bmem=BIO_push(b64,bmem);
    len=BIO_read(bmem,decode,str_len);
    decode[len]=0;
    BIO_free_all(bmem);
    return 0;
}
result is NULL, nothing decoded.

无法解码之前编码的字符串。

我尝试使用这些命令行来测试:

$echo "aaa" | openssl enc -base64 
output: YWFhCg==
$echo "YWFhCg==" | openssl enc -base64 -d
output: aaa

phpopenssl base64_encode有什么区别?这是什么原因造成的?

在 BIO_new() 调用后添加BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL),告诉 OpenSSL 所有输入都显示在一行中,没有换行符。