/*1* SPDX-License-Identifier: ISC2*3* Copyright (c) 2013-2018 Todd C. Miller <[email protected]>4*5* Permission to use, copy, modify, and distribute this software for any6* purpose with or without fee is hereby granted, provided that the above7* copyright notice and this permission notice appear in all copies.8*9* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES10* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF11* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR12* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES13* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN14* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF15* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.16*/1718#include <config.h>1920#include <sudo_compat.h>21#include <sudo_debug.h>22#include <sudo_util.h>2324static const unsigned char base64enc_tab[64] =25"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";2627size_t28sudo_base64_encode_v1(const unsigned char * restrict in, size_t in_len,29char * restrict out, size_t out_len)30{31size_t ii, io;32unsigned int rem, v;33debug_decl(base64_encode, SUDO_DEBUG_UTIL);3435for (io = 0, ii = 0, v = 0, rem = 0; ii < in_len; ii++) {36unsigned char ch = in[ii];37v = (v << 8) | ch;38rem += 8;39while (rem >= 6) {40rem -= 6;41if (io >= out_len)42debug_return_size_t((size_t)-1); /* truncation is failure */43out[io++] = (char)base64enc_tab[(v >> rem) & 63];44}45}46if (rem != 0) {47v <<= (6 - rem);48if (io >= out_len)49debug_return_size_t((size_t)-1); /* truncation is failure */50out[io++] = (char)base64enc_tab[v&63];51}52while (io & 3) {53if (io >= out_len)54debug_return_size_t((size_t)-1); /* truncation is failure */55out[io++] = '=';56}57if (io >= out_len)58debug_return_size_t((size_t)-1); /* no room for NUL terminator */59out[io] = '\0';60debug_return_size_t(io);61}626364