How do I base64 encode (decode) in C?

后端 未结 17 1856
孤城傲影
孤城傲影 2020-11-22 06:27

I have binary data in an unsigned char variable. I need to convert them to PEM base64 in c. I looked in openssl library but i could not find any function. Does any body have

17条回答
  •  猫巷女王i
    2020-11-22 06:33

    In case people need a c++ solution, I put this OpenSSL solution together (for both encode and decode). You'll need to link with the "crypto" library (which is OpenSSL). This has been checked for leaks with valgrind (although you could add some additional error checking code to make it a bit better - I know at least the write function should check for return value).

    #include 
    #include 
    #include 
    
    string base64_encode( const string &str ){
    
        BIO *base64_filter = BIO_new( BIO_f_base64() );
        BIO_set_flags( base64_filter, BIO_FLAGS_BASE64_NO_NL );
    
        BIO *bio = BIO_new( BIO_s_mem() );
        BIO_set_flags( bio, BIO_FLAGS_BASE64_NO_NL );
    
        bio = BIO_push( base64_filter, bio );
    
        BIO_write( bio, str.c_str(), str.length() );
    
        BIO_flush( bio );
    
        char *new_data;
    
        long bytes_written = BIO_get_mem_data( bio, &new_data );
    
        string result( new_data, bytes_written );
        BIO_free_all( bio );
    
        return result;
    
    }
    
    
    
    string base64_decode( const string &str ){
    
        BIO *bio, *base64_filter, *bio_out;
        char inbuf[512];
        int inlen;
        base64_filter = BIO_new( BIO_f_base64() );
        BIO_set_flags( base64_filter, BIO_FLAGS_BASE64_NO_NL );
    
        bio = BIO_new_mem_buf( (void*)str.c_str(), str.length() );
    
        bio = BIO_push( base64_filter, bio );
    
        bio_out = BIO_new( BIO_s_mem() );
    
        while( (inlen = BIO_read(bio, inbuf, 512)) > 0 ){
            BIO_write( bio_out, inbuf, inlen );
        }
    
        BIO_flush( bio_out );
    
        char *new_data;
        long bytes_written = BIO_get_mem_data( bio_out, &new_data );
    
        string result( new_data, bytes_written );
    
        BIO_free_all( bio );
        BIO_free_all( bio_out );
    
        return result;
    
    }
    

提交回复
热议问题