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