Base64 encoding and decoding with OpenSSL

后端 未结 8 2133
天命终不由人
天命终不由人 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:41

    Rather than using the BIO_ interface it's much easier to use the EVP_ interface. For instance:

    #include 
    #include 
    #include 
    
    char *base64(const unsigned char *input, int length) {
      const auto pl = 4*((length+2)/3);
      auto output = reinterpret_cast(calloc(pl+1, 1)); //+1 for the terminating null that EVP_EncodeBlock adds on
      const auto ol = EVP_EncodeBlock(reinterpret_cast(output), input, length);
      if (pl != ol) { std::cerr << "Whoops, encode predicted " << pl << " but we got " << ol << "\n"; }
      return output;
    }
    
    unsigned char *decode64(const char *input, int length) {
      const auto pl = 3*length/4;
      auto output = reinterpret_cast(calloc(pl+1, 1));
      const auto ol = EVP_DecodeBlock(output, reinterpret_cast(input), length);
      if (pl != ol) { std::cerr << "Whoops, decode predicted " << pl << " but we got " << ol << "\n"; }
      return output;
    }
    

    The EVP functions include a streaming interface too, see the man page.

提交回复
热议问题