libadc-cxx 1.0.0
Structured logging for scientific computing
Loading...
Searching...
No Matches
b64.ipp
Go to the documentation of this file.
1#include <openssl/evp.h>
2#include <cstdlib>
3#include <iostream>
4#include <string>
5#include <limits>
6
7// link with -lssl -lcrypto
8
9namespace adc {
10
11// return the output data size to hold encoded data of size input_len
12// including the terminal null byte
13size_t b64_length(size_t input_len)
14{
15 return static_cast<int>(4*((input_len+2)/3) + 1);
16}
17
18// return the output data size to hold decoded data of size input_len
19// including the terminal null byte
20size_t binary_length(size_t input_len)
21{
22 return static_cast<int>(3*input_len/4 + 1);
23}
24
25// return the b64buf pointer populated with the b64 version
26// of the input bytes, or NULL if not possible.
27unsigned char *base64(const unsigned char *binary, size_t binary_len, unsigned char *b64buf, size_t b64buf_length)
28{
29 const size_t pl = b64_length(binary_len);
30 if (!b64buf || b64buf_length < pl || b64buf_length >= std::numeric_limits<int>::max())
31 return NULL;
32 const int ol = EVP_EncodeBlock(b64buf, binary, binary_len);
33 if (ol != static_cast<int>(pl-1)) {
34 std::cerr << "Insufficient space to b64 encode" << std::endl;
35 return NULL;
36 }
37 return b64buf;
38}
39
40// return the binary pointer populated with the binary version
41// of the b64buf base64 bytes, or NULL if not possible.
42unsigned char *decode64(const unsigned char *b64buf, size_t b64buf_length, unsigned char *binary, size_t binary_len)
43{
44 const size_t pl = binary_length(b64buf_length);
45 if (!binary || binary_len < pl || binary_len > std::numeric_limits<int>::max())
46 return NULL;
47 const int ol = EVP_DecodeBlock(binary, b64buf, b64buf_length);
48 if (static_cast<int>(pl-1) != ol) {
49 std::cerr << "Insufficient space to b64 decode;" << std::endl;
50 return NULL;
51 }
52 return binary;
53}
54
55}
Definition adc.hpp:75
unsigned char * decode64(const unsigned char *b64buf, size_t b64buf_length, unsigned char *binary, size_t binary_len)
Definition b64.ipp:42
size_t binary_length(size_t input_len)
Definition b64.ipp:20
unsigned char * base64(const unsigned char *binary, size_t binary_len, unsigned char *b64buf, size_t b64buf_length)
Definition b64.ipp:27
size_t b64_length(size_t input_len)
Definition b64.ipp:13