1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  *   http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 
20 #include <functional>
21 #include <memory>
22 #include <string>
23 
24 #include <openssl/bio.h>
25 #include <openssl/evp.h>
26 
27 #include <thrift/Thrift.h>
28 
29 using std::string;
30 
31 namespace apache {
32 namespace thrift {
33 namespace transport {
34 
base64Encode(unsigned char * data,int length)35 std::string base64Encode(unsigned char* data, int length) {
36   std::unique_ptr<BIO, std::function<void(BIO*)>> base64(BIO_new(BIO_f_base64()),
37                                                          [](BIO* b) { BIO_free_all(b); });
38   BIO_set_flags(base64.get(), BIO_FLAGS_BASE64_NO_NL);
39 
40   BIO* dest = BIO_new(BIO_s_mem());
41   BIO_push(base64.get(), dest);
42   BIO_write(base64.get(), data, length);
43   int ret = BIO_flush(base64.get());
44   THRIFT_UNUSED_VARIABLE(ret);
45 
46   char* encoded;
47   length = BIO_get_mem_data(dest, &encoded);
48   return std::string(encoded, length);
49 }
50 } // namespace transport
51 } // namespace thrift
52 } // namespace apache
53