Index: squid-3.1.23/CREDITS
===================================================================
--- squid-3.1.23.orig/CREDITS
+++ squid-3.1.23/CREDITS
@@ -108,12 +108,41 @@ Access System.  The Harvest copyright te
  *   re-implementations of code complying to this set of standards.  
  */
 
+
 ==============================================================================
 
-lib/base64.c::base64_encode():
+include/base64.h:
+lib/base64.c:
+
+/*
+   Copyright (C) 2002 Niels Möller, Dan Egnor
+
+   This file is part of GNU Nettle.
+
+   GNU Nettle is free software: you can redistribute it and/or
+   modify it under the terms of either:
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at your
+       option) any later version.
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at your
+       option) any later version.
+
+   or both in parallel, as here.
+
+   GNU Nettle is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
 
-Adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c.
-Modified to work with strings instead of files.
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see http://www.gnu.org/licenses/.
+*/
 
 ==============================================================================
 
Index: squid-3.1.23/include/base64.h
===================================================================
--- /dev/null
+++ squid-3.1.23/include/base64.h
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
+ *
+ * Squid software is distributed under GPLv2+ license and includes
+ * contributions from numerous individuals and organizations.
+ * Please see the COPYING and CONTRIBUTORS files for details.
+ */
+
+#ifndef _SQUID_BASE64_H
+#define _SQUID_BASE64_H
+
+/*#if HAVE_NETTLE_BASE64_H && HAVE_NETTLE34_BASE64
+#include <nettle/base64.h>
+
+#else
+*/
+/* Base64 functions copied from Nettle 3.4 under GPLv2, with adjustments */
+
+#include <stdint.h>
+#include <stdlib.h>
+
+/* base64.h
+
+   Base-64 encoding and decoding.
+
+   Copyright (C) 2002 Niels Möller, Dan Egnor
+
+   This file is part of GNU Nettle.
+
+   GNU Nettle is free software: you can redistribute it and/or
+   modify it under the terms of either:
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at your
+       option) any later version.
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at your
+       option) any later version.
+
+   or both in parallel, as here.
+
+   GNU Nettle is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see http://www.gnu.org/licenses/.
+*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Base64 encoding */
+
+/* Maximum length of output for base64_encode_update. NOTE: Doesn't
+ * include any padding that base64_encode_final may add. */
+/* We have at most 4 buffered bits, and a total of (4 + length * 8) bits. */
+#define BASE64_ENCODE_LENGTH(length) (((length) * 8 + 4)/6)
+
+/* Maximum length of output generated by base64_encode_final. */
+#define BASE64_ENCODE_FINAL_LENGTH 3
+
+/* Exact length of output generated by base64_encode_raw, including
+ * padding. */
+#define BASE64_ENCODE_RAW_LENGTH(length) ((((length) + 2)/3)*4)
+
+struct base64_encode_ctx
+{
+    const char *alphabet;    /* Alphabet to use for encoding */
+    unsigned short word;     /* Leftover bits */
+    unsigned char bits;      /* Number of bits, always 0, 2, or 4. */
+};
+
+/* Initialize encoding context for base-64 */
+void
+base64_encode_init(struct base64_encode_ctx *ctx);
+
+/* Initialize encoding context for URL safe alphabet, RFC 4648. */
+void
+base64url_encode_init(struct base64_encode_ctx *ctx);
+
+/* Encodes a single byte. Returns amount of output (always 1 or 2). */
+size_t
+base64_encode_single(struct base64_encode_ctx *ctx,
+                     char *dst,
+                     uint8_t src);
+
+/* Returns the number of output characters. DST should point to an
+ * area of size at least BASE64_ENCODE_LENGTH(length). */
+size_t
+base64_encode_update(struct base64_encode_ctx *ctx,
+                     char *dst,
+                     size_t length,
+                     const uint8_t *src);
+
+/* DST should point to an area of size at least
+ * BASE64_ENCODE_FINAL_LENGTH */
+size_t
+base64_encode_final(struct base64_encode_ctx *ctx,
+                    char *dst);
+
+/* Lower level functions */
+
+/* Encodes a string in one go, including any padding at the end.
+ * Generates exactly BASE64_ENCODE_RAW_LENGTH(length) bytes of output.
+ * Supports overlapped operation, if src <= dst. FIXME: Use of overlap
+ * is deprecated, if needed there should be a separate public fucntion
+ * to do that.*/
+void
+base64_encode_raw(char *dst, size_t length, const uint8_t *src);
+
+void
+base64_encode_group(char *dst, uint32_t group);
+
+/* Base64 decoding */
+
+/* Maximum length of output for base64_decode_update. */
+/* We have at most 6 buffered bits, and a total of (length + 1) * 6 bits. */
+#define BASE64_DECODE_LENGTH(length) ((((length) + 1) * 6) / 8)
+
+struct base64_decode_ctx
+{
+    const signed char *table; /* Decoding table */
+    unsigned short word;      /* Leftover bits */
+    unsigned char bits;       /* Number buffered bits */
+
+    /* Number of padding characters encountered */
+    unsigned char padding;
+};
+
+/* Initialize decoding context for base-64 */
+void
+base64_decode_init(struct base64_decode_ctx *ctx);
+
+/* Initialize encoding context for URL safe alphabet, RFC 4648. */
+void
+base64url_decode_init(struct base64_decode_ctx *ctx);
+
+/* Decodes a single byte. Returns amount of output (0 or 1), or -1 on
+ * errors. */
+int
+base64_decode_single(struct base64_decode_ctx *ctx,
+                     uint8_t *dst,
+                     char src);
+
+/* Returns 1 on success, 0 on error. DST should point to an area of
+ * size at least BASE64_DECODE_LENGTH(length). The amount of data
+ * generated is returned in *DST_LENGTH. */
+int
+base64_decode_update(struct base64_decode_ctx *ctx,
+                     size_t *dst_length,
+                     uint8_t *dst,
+                     size_t src_length,
+                     const char *src);
+
+/* Returns 1 on success. */
+int
+base64_decode_final(struct base64_decode_ctx *ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+// #endif
+/* HAVE_NETTLE_BASE64_H && HAVE_NETTLE34_BASE64 */
+
+/// Calculate the buffer size required to hold the encoded form of
+/// a string of length 'decodedLen' including all terminator bytes.
+#   define base64_encode_len(length) (BASE64_ENCODE_LENGTH(length)+BASE64_ENCODE_FINAL_LENGTH+1)
+
+#endif /* _SQUID_BASE64_H */
+
Index: squid-3.1.23/include/util.h
===================================================================
--- squid-3.1.23.orig/include/util.h
+++ squid-3.1.23/include/util.h
@@ -49,6 +49,8 @@
 #include <arpa/inet.h>
 #endif
 
+#include "base64.h"
+
 #if defined(_SQUID_FREEBSD_)
 #define _etext etext
 #endif
@@ -116,9 +118,6 @@ extern void xmalloc_find_leaks(void);
 #endif
 
 SQUIDCEXTERN time_t parse_iso3307_time(const char *buf);
-SQUIDCEXTERN char *base64_decode(const char *coded);
-SQUIDCEXTERN const char *base64_encode(const char *decoded);
-SQUIDCEXTERN const char *base64_encode_bin(const char *data, int len);
 
 SQUIDCEXTERN double xpercent(double part, double whole);
 SQUIDCEXTERN int xpercentInt(double part, double whole);
Index: squid-3.1.23/lib/base64.c
===================================================================
--- squid-3.1.23.orig/lib/base64.c
+++ squid-3.1.23/lib/base64.c
@@ -1,160 +1,330 @@
 /*
- * $Id$
+ * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
+ *
+ * Squid software is distributed under GPLv2+ license and includes
+ * contributions from numerous individuals and organizations.
+ * Please see the COPYING and CONTRIBUTORS files for details.
  */
 
-#include "config.h"
-#include "util.h"
+/*
+ * Copied from Nettle 3.4 under GPLv2, with adjustments
+ */
+
+// #include "squid.h"
+#include "base64.h"
+#include <assert.h>
+
+#if 1 // !HAVE_NETTLE_BASE64_H || !HAVE_NETTLE34_BASE64
+
+/* base64-encode.c
+
+   Copyright (C) 2002 Niels Möller
+
+   This file is part of GNU Nettle.
+
+   GNU Nettle is free software: you can redistribute it and/or
+   modify it under the terms of either:
+
+     * the GNU Lesser General Public License as published by the Free
+       Software Foundation; either version 3 of the License, or (at your
+       option) any later version.
+
+   or
+
+     * the GNU General Public License as published by the Free
+       Software Foundation; either version 2 of the License, or (at your
+       option) any later version.
+
+   or both in parallel, as here.
+
+   GNU Nettle is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   General Public License for more details.
+
+   You should have received copies of the GNU General Public License and
+   the GNU Lesser General Public License along with this program.  If
+   not, see http://www.gnu.org/licenses/.
+*/
+
+#define TABLE_INVALID -1
+#define TABLE_SPACE -2
+#define TABLE_END -3
+
+static const signed char base64_decode_table[0x100] =
+    {
+        /* White space is HT, VT, FF, CR, LF and SPC */
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -2, -2, -2, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
+        52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -3, -1, -1,
+        -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
+        15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
+        -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+        41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    };
+
+void
+base64_decode_init(struct base64_decode_ctx *ctx)
+{
+
+    ctx->word = ctx->bits = ctx->padding = 0;
+//    ctx->table = base64_decode_table;
+}
+
+int
+base64_decode_single(struct base64_decode_ctx *ctx,
+                     uint8_t *dst,
+                     char src)
+{
+    int data = base64_decode_table[(uint8_t)src]; // ctx->table[(uint8_t) src];
+
+    switch(data)
+    {
+    default:
+        assert(data >= 0 && data < 0x40);
+
+        if (ctx->padding)
+            return -1;
+
+        ctx->word = ctx->word << 6 | data;
+        ctx->bits += 6;
+
+        if (ctx->bits >= 8)
+        {
+            ctx->bits -= 8;
+            dst[0] = ctx->word >> ctx->bits;
+            return 1;
+        }
+        else return 0;
+
+    case TABLE_INVALID:
+        return -1;
+
+    case TABLE_SPACE:
+        return 0;
+
+    case TABLE_END:
+        /* There can be at most two padding characters. */
+        if (!ctx->bits || ctx->padding > 2)
+            return -1;
+
+        if (ctx->word & ( (1<<ctx->bits) - 1))
+            /* We shouldn't have any leftover bits */
+            return -1;
+
+        ctx->padding++;
+        ctx->bits -= 2;
+        return 0;
+    }
+}
 
-#if HAVE_STDIO_H
-#include <stdio.h>
-#endif
-#if HAVE_STDLIB_H
-#include <stdlib.h>
-#endif
-
-
-static void base64_init(void);
-
-static int base64_initialized = 0;
-#define BASE64_VALUE_SZ 256
-#define BASE64_RESULT_SZ 8192
-int base64_value[BASE64_VALUE_SZ];
-const char base64_code[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+int
+base64_decode_update(struct base64_decode_ctx *ctx,
+                     size_t *dst_length,
+                     uint8_t *dst,
+                     size_t src_length,
+                     const char *src)
+{
+    size_t done;
+    size_t i;
+
+    for (i = 0, done = 0; i<src_length; i++)
+        switch(base64_decode_single(ctx, dst + done, src[i]))
+        {
+        case -1:
+            return 0;
+        case 1:
+            done++;
+        /* Fall through */
+        case 0:
+            break;
+        default:
+            abort();
+        }
+
+    assert(done <= BASE64_DECODE_LENGTH(src_length));
+
+    *dst_length = done;
+    return 1;
+}
+
+int
+base64_decode_final(struct base64_decode_ctx *ctx)
+{
+    return ctx->bits == 0;
+}
+
+/* base64-encode.c */
 
+#define ENCODE(alphabet,x) ((alphabet)[0x3F & (x)])
 
 static void
-base64_init(void)
+encode_raw(const char *alphabet,
+           char *dst, size_t length, const uint8_t *src)
 {
-    int i;
+    const uint8_t *in = src + length;
+    char *out = dst + BASE64_ENCODE_RAW_LENGTH(length);
 
-    for (i = 0; i < BASE64_VALUE_SZ; i++)
-        base64_value[i] = -1;
+    unsigned left_over = length % 3;
 
-    for (i = 0; i < 64; i++)
-        base64_value[(int) base64_code[i]] = i;
-    base64_value['='] = 0;
-
-    base64_initialized = 1;
-}
-
-char *
-base64_decode(const char *p)
-{
-    static char result[BASE64_RESULT_SZ];
-    int j;
-    int c;
-    long val;
-    if (!p)
-        return NULL;
-    if (!base64_initialized)
-        base64_init();
-    val = c = 0;
-    for (j = 0; *p && j + 4 < BASE64_RESULT_SZ; p++) {
-        unsigned int k = ((unsigned char) *p) % BASE64_VALUE_SZ;
-        if (base64_value[k] < 0)
-            continue;
-        val <<= 6;
-        val += base64_value[k];
-        if (++c < 4)
-            continue;
-        /* One quantum of four encoding characters/24 bit */
-        result[j++] = (val >> 16) & 0xff;	/* High 8 bits */
-        result[j++] = (val >> 8) & 0xff;	/* Mid 8 bits */
-        result[j++] = val & 0xff;	/* Low 8 bits */
-        val = c = 0;
-    }
-    result[j] = 0;
-    return result;
-}
-
-/* adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments */
-const char *
-base64_encode(const char *decoded_str)
-{
-    static char result[BASE64_RESULT_SZ];
-    int bits = 0;
-    int char_count = 0;
-    int out_cnt = 0;
-    int c;
-
-    if (!decoded_str)
-        return decoded_str;
-
-    if (!base64_initialized)
-        base64_init();
-
-    while ((c = (unsigned char) *decoded_str++) && out_cnt < sizeof(result) - 5) {
-        bits += c;
-        char_count++;
-        if (char_count == 3) {
-            result[out_cnt++] = base64_code[bits >> 18];
-            result[out_cnt++] = base64_code[(bits >> 12) & 0x3f];
-            result[out_cnt++] = base64_code[(bits >> 6) & 0x3f];
-            result[out_cnt++] = base64_code[bits & 0x3f];
-            bits = 0;
-            char_count = 0;
-        } else {
-            bits <<= 8;
+    if (left_over)
+    {
+        in -= left_over;
+        *--out = '=';
+        switch(left_over)
+        {
+        case 1:
+            *--out = '=';
+            *--out = ENCODE(alphabet, (in[0] << 4));
+            break;
+
+        case 2:
+            *--out = ENCODE(alphabet, (in[1] << 2));
+            *--out = ENCODE(alphabet, ((in[0] << 4) | (in[1] >> 4)));
+            break;
+
+        default:
+            abort();
         }
+        *--out = ENCODE(alphabet, (in[0] >> 2));
     }
-    if (char_count != 0) {
-        bits <<= 16 - (8 * char_count);
-        result[out_cnt++] = base64_code[bits >> 18];
-        result[out_cnt++] = base64_code[(bits >> 12) & 0x3f];
-        if (char_count == 1) {
-            result[out_cnt++] = '=';
-            result[out_cnt++] = '=';
-        } else {
-            result[out_cnt++] = base64_code[(bits >> 6) & 0x3f];
-            result[out_cnt++] = '=';
-        }
+
+    while (in > src)
+    {
+        in -= 3;
+        *--out = ENCODE(alphabet, (in[2]));
+        *--out = ENCODE(alphabet, ((in[1] << 2) | (in[2] >> 6)));
+        *--out = ENCODE(alphabet, ((in[0] << 4) | (in[1] >> 4)));
+        *--out = ENCODE(alphabet, (in[0] >> 2));
     }
-    result[out_cnt] = '\0';	/* terminate */
-    return result;
+    assert(in == src);
+    assert(out == dst);
 }
 
-/* adopted from http://ftp.sunet.se/pub2/gnu/vm/base64-encode.c with adjustments */
-const char *
-base64_encode_bin(const char *data, int len)
-{
-    static char result[BASE64_RESULT_SZ];
-    int bits = 0;
-    int char_count = 0;
-    int out_cnt = 0;
-
-    if (!data)
-        return data;
-
-    if (!base64_initialized)
-        base64_init();
-
-    while (len-- && out_cnt < sizeof(result) - 5) {
-        int c = (unsigned char) *data++;
-        bits += c;
-        char_count++;
-        if (char_count == 3) {
-            result[out_cnt++] = base64_code[bits >> 18];
-            result[out_cnt++] = base64_code[(bits >> 12) & 0x3f];
-            result[out_cnt++] = base64_code[(bits >> 6) & 0x3f];
-            result[out_cnt++] = base64_code[bits & 0x3f];
-            bits = 0;
-            char_count = 0;
-        } else {
-            bits <<= 8;
-        }
+static const char base64_encode_table[64] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+    "abcdefghijklmnopqrstuvwxyz"
+    "0123456789+/";
+
+void
+base64_encode_raw(char *dst, size_t length, const uint8_t *src)
+{
+    encode_raw(base64_encode_table, dst, length, src);
+}
+
+void
+base64_encode_group(char *dst, uint32_t group)
+{
+    *dst++ = ENCODE(base64_encode_table, (group >> 18));
+    *dst++ = ENCODE(base64_encode_table, (group >> 12));
+    *dst++ = ENCODE(base64_encode_table, (group >> 6));
+    *dst++ = ENCODE(base64_encode_table, group);
+}
+
+void
+base64_encode_init(struct base64_encode_ctx *ctx)
+{
+    ctx->word = ctx->bits = 0;
+    ctx->alphabet = base64_encode_table;
+}
+
+/* Encodes a single byte. */
+size_t
+base64_encode_single(struct base64_encode_ctx *ctx,
+                     char *dst,
+                     uint8_t src)
+{
+    unsigned done = 0;
+    unsigned word = ctx->word << 8 | src;
+    unsigned bits = ctx->bits + 8;
+
+    while (bits >= 6)
+    {
+        bits -= 6;
+        dst[done++] = ENCODE(ctx->alphabet, (word >> bits));
     }
-    if (char_count != 0) {
-        bits <<= 16 - (8 * char_count);
-        result[out_cnt++] = base64_code[bits >> 18];
-        result[out_cnt++] = base64_code[(bits >> 12) & 0x3f];
-        if (char_count == 1) {
-            result[out_cnt++] = '=';
-            result[out_cnt++] = '=';
-        } else {
-            result[out_cnt++] = base64_code[(bits >> 6) & 0x3f];
-            result[out_cnt++] = '=';
-        }
+
+    ctx->bits = bits;
+    ctx->word = word;
+
+    assert(done <= 2);
+
+    return done;
+}
+
+/* Returns the number of output characters. DST should point to an
+ * area of size at least BASE64_ENCODE_LENGTH(length). */
+size_t
+base64_encode_update(struct base64_encode_ctx *ctx,
+                     char *dst,
+                     size_t length,
+                     const uint8_t *src)
+{
+    size_t done = 0;
+    size_t left = length;
+    unsigned left_over;
+    size_t bulk;
+
+    while (ctx->bits && left)
+    {
+        left--;
+        done += base64_encode_single(ctx, dst + done, *src++);
     }
-    result[out_cnt] = '\0';	/* terminate */
-    return result;
+
+    left_over = left % 3;
+    bulk = left - left_over;
+
+    if (bulk)
+    {
+        assert(!(bulk % 3));
+
+        encode_raw(ctx->alphabet, dst + done, bulk, src);
+        done += BASE64_ENCODE_RAW_LENGTH(bulk);
+        src += bulk;
+        left = left_over;
+    }
+
+    while (left)
+    {
+        left--;
+        done += base64_encode_single(ctx, dst + done, *src++);
+    }
+
+    assert(done <= BASE64_ENCODE_LENGTH(length));
+
+    return done;
+}
+
+/* DST should point to an area of size at least
+ * BASE64_ENCODE_FINAL_SIZE */
+size_t
+base64_encode_final(struct base64_encode_ctx *ctx,
+                    char *dst)
+{
+    unsigned done = 0;
+    unsigned bits = ctx->bits;
+
+    if (bits)
+    {
+        dst[done++] = ENCODE(ctx->alphabet, (ctx->word << (6 - ctx->bits)));
+        for (; bits < 6; bits += 2)
+            dst[done++] = '=';
+
+        ctx->bits = 0;
+    }
+
+    assert(done <= BASE64_ENCODE_FINAL_LENGTH);
+    return done;
 }
+
+#endif /* !HAVE_NETTLE_BASE64_H || !HAVE_NETTLE34_BASE64 */
+
Index: squid-3.1.23/lib/ntlmauth.c
===================================================================
--- squid-3.1.23.orig/lib/ntlmauth.c
+++ squid-3.1.23/lib/ntlmauth.c
@@ -128,7 +128,6 @@ ntlm_make_challenge(char *domain, char *
 {
     ntlm_challenge ch;
     int pl = 0;
-    const char *encoded;
     memset(&ch, 0, sizeof(ntlm_challenge));	/* reset */
     memcpy(ch.signature, "NTLMSSP", 8);		/* set the signature */
     ch.type = htole32(NTLM_CHALLENGE);	/* this is a challenge */
@@ -146,6 +145,21 @@ ntlm_make_challenge(char *domain, char *
     ch.context_low = 0;		/* check this out */
     ch.context_high = 0;
     memcpy(ch.challenge, challenge_nonce, challenge_nonce_len);
-    encoded = base64_encode_bin((char *) &ch, NTLM_CHALLENGE_HEADER_OFFSET + pl);
-    return encoded;
+
+    size_t len = NTLM_CHALLENGE_HEADER_OFFSET + pl;
+    // for lack of a good NTLM token size limit, allow up to what the helper input can be
+    // validations later will expect to be limited to that size.
+    const int HELPER_INPUT_BUFFER = 8192;
+    static char b64buf[HELPER_INPUT_BUFFER-10]; /* 10 for other line fields, delimiters and terminator */
+    if (base64_encode_len(len) < sizeof(b64buf)-1) {
+        fprintf(stderr, "base64 encoding of the token challenge will exceed %u bytes", (unsigned int)sizeof(b64buf));
+        return NULL;
+    }
+
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+    size_t blen = base64_encode_update(&ctx, b64buf, len, (const uint8_t*)(&ch));
+    blen += base64_encode_final(&ctx, b64buf+blen);
+    b64buf[blen] = '\0';
+    return (const char*)(b64buf);
 }
Index: squid-3.1.23/src/HttpHeader.cc
===================================================================
--- squid-3.1.23.orig/src/HttpHeader.cc
+++ squid-3.1.23/src/HttpHeader.cc
@@ -1399,7 +1399,16 @@ HttpHeader::getAuth(http_hdr_type id, co
     if (!*field)		/* no authorization cookie */
         return NULL;
 
-    return base64_decode(field);
+     static char decodedAuthToken[8192];
+     struct base64_decode_ctx ctx;
+     base64_decode_init(&ctx);
+     size_t decodedLen = 0;
+     if (!base64_decode_update(&ctx, &decodedLen, reinterpret_cast<uint8_t*>(decodedAuthToken), strlen(field), field) ||
+             !base64_decode_final(&ctx)) {
+         return NULL;
+     }
+     decodedAuthToken[decodedLen] = '\0';
+     return decodedAuthToken;
 }
 
 ETag
Index: squid-3.1.23/src/adaptation/icap/ModXact.cc
===================================================================
--- squid-3.1.23.orig/src/adaptation/icap/ModXact.cc
+++ squid-3.1.23/src/adaptation/icap/ModXact.cc
@@ -1300,14 +1300,23 @@ void Adaptation::Icap::ModXact::makeRequ
 
 void Adaptation::Icap::ModXact::makeUsernameHeader(const HttpRequest *request, MemBuf &buf)
 {
-    if (const AuthUserRequest *auth = request->auth_user_request) {
-        if (char const *name = auth->username()) {
-            const char *value = TheConfig.client_username_encode ?
-                                base64_encode(name) : name;
-            buf.Printf("%s: %s\r\n", TheConfig.client_username_header,
-                       value);
-        }
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+
+    const char *value = NULL;
+    if (request->auth_user_request != NULL) {
+        value = request->auth_user_request->username();
     }
+
+    if (value) {
+        if (TheConfig.client_username_encode) {
+            char base64buf[base64_encode_len(MAX_LOGIN_SZ)];
+            size_t resultLen = base64_encode_update(&ctx, base64buf, strlen(value), reinterpret_cast<const uint8_t*>(value));
+            resultLen += base64_encode_final(&ctx, base64buf+resultLen);
+            buf.Printf("%s: %.*s\r\n", TheConfig.client_username_header, (int)resultLen, base64buf);
+        } else
+            buf.Printf("%s: %s\r\n", TheConfig.client_username_header, value);
+     }
 }
 
 void Adaptation::Icap::ModXact::encapsulateHead(MemBuf &icapBuf, const char *section, MemBuf &httpBuf, const HttpMsg *head)
Index: squid-3.1.23/src/auth/digest/auth_digest.cc
===================================================================
--- squid-3.1.23.orig/src/auth/digest/auth_digest.cc
+++ squid-3.1.23/src/auth/digest/auth_digest.cc
@@ -129,7 +129,11 @@ authDigestNonceEncode(digest_nonce_h * n
     if (nonce->key)
         xfree(nonce->key);
 
-    nonce->key = xstrdup(base64_encode_bin((char *) &(nonce->noncedata), sizeof(digest_nonce_data)));
+    nonce->key = xcalloc(base64_encode_len(sizeof(digest_nonce_data)), 1);
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+    size_t blen = base64_encode_update(&ctx, (char*)nonce->key, sizeof(digest_nonce_data), reinterpret_cast<const uint8_t*>(&(nonce->noncedata)));
+    blen += base64_encode_final(&ctx, (char*)nonce->key+blen);
 }
 
 static digest_nonce_h *
Index: squid-3.1.23/src/http.cc
===================================================================
--- squid-3.1.23.orig/src/http.cc
+++ squid-3.1.23/src/http.cc
@@ -1561,6 +1561,11 @@ HttpStateData::httpBuildRequestHeader(Ht
     }
 #endif
 
+    char loginbuf[base64_encode_len(MAX_LOGIN_SZ)];
+    size_t blen;
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+
     /** \pre Handle X-Forwarded-For */
     if (strcmp(opt_forwarded_for, "delete") != 0) {
 
@@ -1620,8 +1625,14 @@ HttpStateData::httpBuildRequestHeader(Ht
     /* append Authorization if known in URL, not in header and going direct */
     if (!hdr_out->has(HDR_AUTHORIZATION)) {
         if (!request->flags.proxying && *request->login) {
-            httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
-                              base64_encode(request->login));
+            static char result[base64_encode_len(MAX_URL*2)]; // should be big enough for a single URI segment
+            struct base64_encode_ctx ctx;
+            base64_encode_init(&ctx);
+            size_t blen = base64_encode_update(&ctx, result, strnlen(request->login, sizeof(request->login)), reinterpret_cast<const uint8_t*>(request->login));
+            blen += base64_encode_final(&ctx, result+blen);
+            result[blen] = '\0';
+            if (blen)
+                httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %.*s", (int)blen, result);
         }
     }
 
@@ -1630,7 +1641,6 @@ HttpStateData::httpBuildRequestHeader(Ht
             !hdr_out->has(HDR_PROXY_AUTHORIZATION)) {
         if (*orig_request->peer_login == '*') {
             /* Special mode, to pass the username to the upstream cache */
-            char loginbuf[256];
             const char *username = "-";
 
             if (orig_request->extacl_user.size())
@@ -1638,24 +1648,26 @@ HttpStateData::httpBuildRequestHeader(Ht
             else if (orig_request->auth_user_request)
                 username = orig_request->auth_user_request->username();
 
-            snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
+            blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
+            blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
+            blen += base64_encode_final(&ctx, loginbuf+blen);
+            httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %.*s", (int)blen, loginbuf);
 
-            httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
-                              base64_encode(loginbuf));
         } else if (strcmp(orig_request->peer_login, "PASS") == 0) {
             if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
-                char loginbuf[256];
-                snprintf(loginbuf, sizeof(loginbuf), SQUIDSTRINGPH ":" SQUIDSTRINGPH,
-                         SQUIDSTRINGPRINT(orig_request->extacl_user),
-                         SQUIDSTRINGPRINT(orig_request->extacl_passwd));
-                httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
-                                  base64_encode(loginbuf));
+
+                blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
+                blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
+                blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
+                blen += base64_encode_final(&ctx, loginbuf+blen);
+                httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %.*s", (int)blen, loginbuf);
             }
         } else if (strcmp(orig_request->peer_login, "PROXYPASS") == 0) {
             /* Nothing to do */
         } else {
-            httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %s",
-                              base64_encode(orig_request->peer_login));
+            blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
+            blen += base64_encode_final(&ctx, loginbuf+blen);
+            httpHeaderPutStrf(hdr_out, HDR_PROXY_AUTHORIZATION, "Basic %.*s", (int)blen, loginbuf);
         }
     }
 
@@ -1673,16 +1685,15 @@ HttpStateData::httpBuildRequestHeader(Ht
             if (auth && strncasecmp(auth, "basic ", 6) == 0) {
                 hdr_out->putStr(HDR_AUTHORIZATION, auth);
             } else if (orig_request->extacl_user.size() && orig_request->extacl_passwd.size()) {
-                char loginbuf[256];
-                snprintf(loginbuf, sizeof(loginbuf), SQUIDSTRINGPH ":" SQUIDSTRINGPH,
-                         SQUIDSTRINGPRINT(orig_request->extacl_user),
-                         SQUIDSTRINGPRINT(orig_request->extacl_passwd));
-                httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
-                                  base64_encode(loginbuf));
+
+                blen = base64_encode_update(&ctx, loginbuf, request->extacl_user.size(), reinterpret_cast<const uint8_t*>(request->extacl_user.rawBuf()));
+                blen += base64_encode_update(&ctx, loginbuf+blen, 1, reinterpret_cast<const uint8_t*>(":"));
+                blen += base64_encode_update(&ctx, loginbuf+blen, request->extacl_passwd.size(), reinterpret_cast<const uint8_t*>(request->extacl_passwd.rawBuf()));
+                blen += base64_encode_final(&ctx, loginbuf+blen);
+                httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %.*s", (int)blen, loginbuf);
             }
         } else if (*orig_request->peer_login == '*') {
             /* Special mode, to pass the username to the upstream cache */
-            char loginbuf[256];
             const char *username = "-";
 
             if (orig_request->auth_user_request)
@@ -1690,14 +1701,15 @@ HttpStateData::httpBuildRequestHeader(Ht
             else if (orig_request->extacl_user.size())
                 username = orig_request->extacl_user.termedBuf();
 
-            snprintf(loginbuf, sizeof(loginbuf), "%s%s", username, orig_request->peer_login + 1);
-
-            httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
-                              base64_encode(loginbuf));
+            blen = base64_encode_update(&ctx, loginbuf, strlen(username), reinterpret_cast<const uint8_t*>(username));
+            blen += base64_encode_update(&ctx, loginbuf+blen, strlen(request->peer_login +1), reinterpret_cast<const uint8_t*>(request->peer_login +1));
+            blen += base64_encode_final(&ctx, loginbuf+blen);
+            httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %.*s", (int)blen, loginbuf);
         } else {
             /* Fixed login string */
-            httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %s",
-                              base64_encode(orig_request->peer_login));
+            blen = base64_encode_update(&ctx, loginbuf, strlen(request->peer_login), reinterpret_cast<const uint8_t*>(request->peer_login));
+            blen += base64_encode_final(&ctx, loginbuf+blen);
+            httpHeaderPutStrf(hdr_out, HDR_AUTHORIZATION, "Basic %.*s", (int)blen, loginbuf);
         }
     }
 
Index: squid-3.1.23/tools/cachemgr.cc
===================================================================
--- squid-3.1.23.orig/tools/cachemgr.cc
+++ squid-3.1.23/tools/cachemgr.cc
@@ -1072,7 +1072,7 @@ make_pub_auth(cachemgr_request * req)
         return;
 
     /* host | time | user | passwd */
-    snprintf(buf, sizeof(buf), "%s|%d|%s|%s",
+    const int bufLen = snprintf(buf, sizeof(buf), "%s|%d|%s|%s",
              req->hostname,
              (int) now,
              rfc1738_escape(safe_str(req->user_name)),
@@ -1080,9 +1080,16 @@ make_pub_auth(cachemgr_request * req)
 
     debug(3) fprintf(stderr, "cmgr: pre-encoded for pub: %s\n", buf);
 
-    debug(3) fprintf(stderr, "cmgr: encoded: '%s'\n", base64_encode(buf));
+    const int encodedLen = BASE64_ENCODE_LENGTH(bufLen);
+    req->pub_auth = (char *) xmalloc(encodedLen);
 
-    req->pub_auth = xstrdup(base64_encode(buf));
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+    size_t blen = base64_encode_update(&ctx, req->pub_auth, bufLen, reinterpret_cast<uint8_t*>(buf));
+    blen += base64_encode_final(&ctx, req->pub_auth+blen);
+    req->pub_auth[blen] = '\0';
+
+    debug(3) fprintf(stderr, "cmgr: encoded: '%s'\n", req->pub_auth);
 }
 
 static void
@@ -1098,7 +1105,16 @@ decode_pub_auth(cachemgr_request * req)
     if (!req->pub_auth || strlen(req->pub_auth) < 4 + strlen(safe_str(req->hostname)))
         return;
 
-    buf = xstrdup(base64_decode(req->pub_auth));
+    size_t decodedLen = BASE64_DECODE_LENGTH(strlen(req->pub_auth));
+    buf = (char*)xmalloc(decodedLen);
+    struct base64_decode_ctx ctx;
+    base64_decode_init(&ctx);
+    base64_decode_update(&ctx, &decodedLen, reinterpret_cast<uint8_t*>(buf), strlen(req->pub_auth), req->pub_auth);
+    if (!base64_decode_final(&ctx)) {
+        debug(1) fprintf(stderr, "cmgr: base64 decode failure. Incomplete auth token string.\n");
+        xfree(buf);
+        return;
+    }
 
     debug(3) fprintf(stderr, "cmgr: length ok\n");
 
@@ -1174,15 +1190,29 @@ make_auth_header(const cachemgr_request
     if (!req->passwd)
         return "";
 
-    snprintf(buf, sizeof(buf), "%s:%s",
+    int bufLen = snprintf(buf, sizeof(buf), "%s:%s",
              req->user_name ? req->user_name : "",
              req->passwd);
 
-    stringLength += snprintf(buf, sizeof(buf), "Authorization: Basic %s\r\n", base64_encode(buf));
+    int encodedLen = base64_encode_len(bufLen);
+    if (encodedLen <= 0)
+        return "";
+
 
+    char *str64 = (char*)xmalloc(encodedLen);
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+    size_t blen = base64_encode_update(&ctx, str64, bufLen, reinterpret_cast<uint8_t*>(buf));
+    blen += base64_encode_final(&ctx, str64+blen);
+    str64[blen] = '\0';
+    
+    stringLength += snprintf(buf, sizeof(buf), "Authorization: Basic %.*s\r\n", (int)blen, str64);
+ 
     assert(stringLength < sizeof(buf));
+ 
+    snprintf(&buf[stringLength], sizeof(buf) - stringLength, "Proxy-Authorization: Basic %.*s\r\n", (int)blen, str64);
 
-    snprintf(&buf[stringLength], sizeof(buf) - stringLength, "Proxy-Authorization: Basic %s\r\n", base64_encode(buf));
+    xfree(str64);
 
     return buf;
 }
Index: squid-3.1.23/helpers/ntlm_auth/fakeauth/fakeauth_auth.c
===================================================================
--- squid-3.1.23.orig/helpers/ntlm_auth/fakeauth/fakeauth_auth.c
+++ squid-3.1.23/helpers/ntlm_auth/fakeauth/fakeauth_auth.c
@@ -62,7 +62,7 @@ int NTLM_packet_debug_enabled = 0;
 /* XXX this is not done cleanly... */
 
 static void
-hex_dump(void *data, int size)
+hex_dump(const void *data, int size)
 {
     /* dumps size bytes of *data to stdout. Looks like:
      * [0000] 75 6E 6B 6E 6F 77 6E 20
@@ -74,7 +74,7 @@ hex_dump(void *data, int size)
         return;
 
     if (debug_enabled) {
-        unsigned char *p = data;
+        const unsigned char *p = data;
         unsigned char c;
         int n;
         char bytestr[4] = {0};
@@ -367,13 +367,52 @@ process_options(int argc, char *argv[])
         exit(1);
 }
 
+static const char * base64_decode(const char *data)
+{
+    static char res[BUFFER_SIZE];
+    size_t res_len = BUFFER_SIZE;
+    size_t len = strnlen(data, BUFFER_SIZE);
+    struct base64_decode_ctx ctx;
+
+    base64_decode_init(&ctx);
+    if (base64_decode_update(&ctx, &res_len, (uint8_t*)res, len, data) &&
+        base64_decode_final(&ctx)) {
+
+        res[res_len] = '\x00';
+    }
+    else {
+        res[0] = '\x00';
+    }
+
+    return res;
+}
+
+static const char * base64_encode_bin(const char *data, size_t len)
+{
+    static char res[BUFFER_SIZE];
+    size_t res_len;
+    struct base64_encode_ctx ctx;
+
+    res[0] = '\x00';
+    if (BASE64_ENCODE_LENGTH(len) >= BUFFER_SIZE + 1)
+        return res;
+
+    base64_encode_init(&ctx);
+    res_len = base64_encode_update(&ctx, res, len, (const uint8_t*)data);
+    res_len += base64_encode_final(&ctx, res + res_len);
+    res[res_len] = '\x00';
+
+    return res;
+}
+
 
 int
 main(int argc, char *argv[])
 {
     char buf[BUFFER_SIZE];
     int buflen = 0;
-    char user[256], *p, *decoded = NULL;
+    char user[256], *p;
+    const char *decoded = NULL;
     struct ntlm_challenge chal;
     struct ntlm_negotiate *nego;
     char helper_command[3];
Index: squid-3.1.23/helpers/ntlm_auth/smb_lm/ntlm_smb_lm_auth.c
===================================================================
--- squid-3.1.23.orig/helpers/ntlm_auth/smb_lm/ntlm_smb_lm_auth.c
+++ squid-3.1.23/helpers/ntlm_auth/smb_lm/ntlm_smb_lm_auth.c
@@ -284,8 +284,9 @@ manage_request()
 {
     ntlmhdr *fast_header;
     char buf[BUFFER_SIZE];
+    uint8_t decoded[BUFFER_SIZE];
     const char *ch;
-    char *ch2, *decoded, *cred = NULL;
+    char *ch2, *cred = NULL;
     int plen;
 
     if (fgets(buf, BUFFER_SIZE, stdin) == NULL) {
@@ -303,15 +304,22 @@ manage_request()
 
     if (memcmp(buf, "KK ", 3) == 0) {	/* authenticate-request */
         /* figure out what we got */
-        decoded = base64_decode(buf + 3);
-        /* Note: we don't need to manage memory at this point, since
-         *  base64_decode returns a pointer to static storage.
-         */
+        struct base64_decode_ctx ctx;
+        base64_decode_init(&ctx);
+        size_t dstLen = 0;
+        int decodedLen = 0;
+        if (!base64_decode_update(&ctx, &dstLen, decoded, strlen(buf)-3, buf+3) ||
+                !base64_decode_final(&ctx)) {
+            SEND("NA Packet format error, couldn't base64-decode");
+            return;
+        }
+        decodedLen = dstLen;
 
-        if (!decoded) {		/* decoding failure, return error */
+        if ((size_t)decodedLen < sizeof(ntlmhdr)) { /* decoding failure, return error */
             SEND("NA Packet format error, couldn't base64-decode");
             return;
         }
+
         /* fast-track-decode request type. */
         fast_header = (struct _ntlmhdr *) decoded;
 
Index: squid-3.1.23/tools/squidclient.cc
===================================================================
--- squid-3.1.23.orig/tools/squidclient.cc
+++ squid-3.1.23/tools/squidclient.cc
@@ -165,6 +165,28 @@ usage(const char *progname)
     exit(1);
 }
 
+static const char* base64_auth_str(const char *user, const char *pw)
+{
+    struct base64_encode_ctx ctx;
+    base64_encode_init(&ctx);
+    size_t len = BASE64_ENCODE_LENGTH(strlen(user) + 1 + strlen(pw));
+    static char buf[BUFSIZ];
+
+    assert(len < BUFSIZ);
+
+    size_t bsize = 0;
+    bsize += base64_encode_update(&ctx, buf, strlen(user), reinterpret_cast<const uint8_t*>(user));
+    bsize += base64_encode_update(&ctx, buf+bsize, 1, reinterpret_cast<const uint8_t*>(":"));
+    bsize += base64_encode_update(&ctx, buf+bsize, strlen(pw), reinterpret_cast<const uint8_t*>(pw));
+    bsize += base64_encode_final(&ctx, buf+bsize);
+    assert(bsize < len); // paranoid and late but better than nothing
+
+    buf[bsize] = '\x00';
+
+    return buf;
+}
+
+
 static int interrupted = 0;
 int
 main(int argc, char *argv[])
@@ -442,8 +464,7 @@ main(int argc, char *argv[])
                 fprintf(stderr, "ERROR: Proxy password missing\n");
                 exit(1);
             }
-            snprintf(buf, BUFSIZ, "%s:%s", user, password);
-            snprintf(buf, BUFSIZ, "Proxy-Authorization: Basic %s\r\n", base64_encode(buf));
+            snprintf(buf, BUFSIZ, "Proxy-Authorization: Basic %s\r\n", base64_auth_str(user, password));
             strcat(msg, buf);
         }
         if (www_user) {
@@ -457,8 +478,7 @@ main(int argc, char *argv[])
                 fprintf(stderr, "ERROR: WWW password missing\n");
                 exit(1);
             }
-            snprintf(buf, BUFSIZ, "%s:%s", user, password);
-            snprintf(buf, BUFSIZ, "Authorization: Basic %s\r\n", base64_encode(buf));
+            snprintf(buf, BUFSIZ, "Authorization: Basic %s\r\n", base64_auth_str(user, password));
             strcat(msg, buf);
         }
 
