proxygen
CryptUtil.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2015-present, Facebook, Inc.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree. An additional grant
7  * of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
11 
12 #include <iomanip>
14 #include <openssl/buffer.h>
15 #include <openssl/md5.h>
16 #include <sstream>
17 
18 namespace proxygen {
19 
20 // Base64 encode using openssl
22  std::string result;
23  BIO *b64 = BIO_new(BIO_f_base64());
24  if (b64 == nullptr) {
25  return result;
26  }
27  BIO *bmem = BIO_new(BIO_s_mem());
28  if (bmem == nullptr) {
29  BIO_free_all(b64);
30  return result;
31  }
32  BUF_MEM *bptr;
33 
34  // chain base64 filter with the memory buffer
35  // so that text will be encoded by base64 and flushed to buffer
36  BIO *chain = BIO_push(b64, bmem);
37  if (chain == nullptr) {
38  BIO_free_all(b64);
39  return result;
40  }
41  BIO_set_flags(chain, BIO_FLAGS_BASE64_NO_NL);
42  BIO_write(chain, text.begin(), text.size());
43  if (BIO_flush(chain) != 1) {
44  BIO_free_all(chain);
45  return result;
46  }
47 
48  BIO_get_mem_ptr(chain, &bptr);
49 
50  if (bptr && bptr->length > 0) {
51  result = std::string((char *)bptr->data, bptr->length);
52  }
53 
54  // free the whole BIO chain (b64 and mem)
55  BIO_free_all(chain);
56  return result;
57 }
58 
59 // MD5 encode using openssl
61  static_assert(MD5_DIGEST_LENGTH == 16, "");
62 
63  unsigned char digest[MD5_DIGEST_LENGTH];
64  MD5(text.begin(), text.size(), digest);
65 
66  // convert digest to hex string
67  std::ostringstream ss;
68  ss << std::hex << std::setfill('0');
69  for(int i = 0; i < MD5_DIGEST_LENGTH; i++) {
70  ss << std::setw(2) << (unsigned int)digest[i];
71  }
72  return ss.str();
73 }
74 
75 }
constexpr size_type size() const
Definition: Range.h:431
std::string base64Encode(folly::ByteRange text)
Definition: CryptUtil.cpp:21
std::string md5Encode(folly::ByteRange text)
Definition: CryptUtil.cpp:60
constexpr Iter begin() const
Definition: Range.h:452
const char * string
Definition: Conv.cpp:212