How do I base64 encode (decode) in C?

后端 未结 17 1503
孤城傲影
孤城傲影 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条回答
  •  名媛妹妹
    2020-11-22 06:54

    The EVP_EncodeBlock and EVP_DecodeBlock functions make it very easy:

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

提交回复
热议问题