Base64 encoding and decoding with OpenSSL

后端 未结 8 2123
天命终不由人
天命终不由人 2020-12-07 19:22

I\'ve been trying to figure out the openssl documentation for base64 decoding and encoding. I found some code snippets below



        
8条回答
  •  北海茫月
    2020-12-07 19:59

    Here is an example of OpenSSL base64 encode/decode I wrote:

    Notice, I have some macros/classes in the code that I wrote, but none of them is important for the example. It is simply some C++ wrappers I wrote:

    buffer base64::encode( const buffer& data )
    {
        // bio is simply a class that wraps BIO* and it free the BIO in the destructor.
    
        bio b64(BIO_f_base64()); // create BIO to perform base64
        BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
    
        bio mem(BIO_s_mem()); // create BIO that holds the result
    
        // chain base64 with mem, so writing to b64 will encode base64 and write to mem.
        BIO_push(b64, mem);
    
        // write data
        bool done = false;
        int res = 0;
        while(!done)
        {
            res = BIO_write(b64, data.data, (int)data.size);
    
            if(res <= 0) // if failed
            {
                if(BIO_should_retry(b64)){
                    continue;
                }
                else // encoding failed
                {
                    /* Handle Error!!! */
                }
            }
            else // success!
                done = true;
        }
    
        BIO_flush(b64);
    
        // get a pointer to mem's data
        char* dt;
        long len = BIO_get_mem_data(mem, &dt);
    
        // assign data to output
        std::string s(dt, len);
    
        return buffer(s.length()+sizeof(char), (byte*)s.c_str());
    }
    

提交回复
热议问题