Commit 223c9f05 authored by jan.koester's avatar jan.koester
Browse files

crypto: add MD4, MD5 and HMAC-MD5

Legacy-interop only (NTLM NT hash / NTLMv2, CRAM-MD5, APOP) -- needed
for Exchange-style AUTH=NTLM in libimappp. New crypto/md.h, verified
against RFC 1320/1321 A.5 and RFC 2202 HMAC-MD5 vectors (test/md_test).

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent c228701a
Loading
Loading
Loading
Loading
+2 −0
Changes for src/CMakeLists.txt: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line

list(APPEND netplussrc
    crypto/sha.cpp
    crypto/md.cpp
    crypto/base64.cpp
    crypto/des.cpp
    crypto/aes.cpp
@@ -81,6 +82,7 @@ set(headers
    crypto/rsa_pkcs1_sha384.h
    crypto/ecdsa_verify.h
    crypto/sha.h
    crypto/md.h
    crypto/pkcs12.h
    crypto/tls.h
    crypto/curve25519.h

src/crypto/md.cpp

0 → 100644
+169 −0
Changes for src/crypto/md.cpp: 169 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <cstring>

#include "md.h"

namespace {

inline uint32_t rotl32(uint32_t x, int s) { return (x << s) | (x >> (32 - s)); }

inline uint32_t load_le32(const uint8_t *p) {
    return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
}

inline void store_le32(uint8_t *p, uint32_t v) {
    p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
}

// MD4 and MD5 share the same Merkle-Damgard framing: 64-byte blocks, little-endian words,
// 0x80 pad + 64-bit little-endian bit length, 4-word little-endian state.
template <typename Compress>
std::vector<uint8_t> md_frame(const std::vector<uint8_t> &input, Compress compress) {
    uint32_t st[4] = {0x67452301u, 0xefcdab89u, 0x98badcfeu, 0x10325476u};

    const size_t n = input.size();
    size_t off = 0;
    for (; off + 64 <= n; off += 64) compress(st, input.data() + off);

    uint8_t tail[128];
    size_t rem = n - off;
    if (rem) std::memcpy(tail, input.data() + off, rem);
    tail[rem] = 0x80;
    size_t tailLen = (rem < 56) ? 64 : 128;
    std::memset(tail + rem + 1, 0, tailLen - rem - 1);
    uint64_t bits = (uint64_t)n * 8u;
    for (int i = 0; i < 8; ++i) tail[tailLen - 8 + i] = (uint8_t)(bits >> (8 * i));
    compress(st, tail);
    if (tailLen == 128) compress(st, tail + 64);

    std::vector<uint8_t> out(16);
    for (int i = 0; i < 4; ++i) store_le32(out.data() + 4 * i, st[i]);
    return out;
}

void md4_compress(uint32_t st[4], const uint8_t *blk) {
    uint32_t X[16];
    for (int i = 0; i < 16; ++i) X[i] = load_le32(blk + 4 * i);
    uint32_t a = st[0], b = st[1], c = st[2], d = st[3];

    auto F = [](uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (~x & z); };
    auto G = [](uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (x & z) | (y & z); };
    auto H = [](uint32_t x, uint32_t y, uint32_t z) { return x ^ y ^ z; };

    static const int r1s[4] = {3, 7, 11, 19};
    for (int i = 0; i < 16; ++i) {
        uint32_t t = rotl32(a + F(b, c, d) + X[i], r1s[i % 4]);
        a = d; d = c; c = b; b = t;
    }
    static const int r2s[4] = {3, 5, 9, 13};
    static const int r2x[16] = {0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15};
    for (int i = 0; i < 16; ++i) {
        uint32_t t = rotl32(a + G(b, c, d) + X[r2x[i]] + 0x5a827999u, r2s[i % 4]);
        a = d; d = c; c = b; b = t;
    }
    static const int r3s[4] = {3, 9, 11, 15};
    static const int r3x[16] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
    for (int i = 0; i < 16; ++i) {
        uint32_t t = rotl32(a + H(b, c, d) + X[r3x[i]] + 0x6ed9eba1u, r3s[i % 4]);
        a = d; d = c; c = b; b = t;
    }
    st[0] += a; st[1] += b; st[2] += c; st[3] += d;
}

void md5_compress(uint32_t st[4], const uint8_t *blk) {
    static const uint32_t K[64] = {
        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
        0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
        0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
        0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
        0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
        0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
        0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
    static const int S[64] = {
        7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
        5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
        4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
        6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};

    uint32_t M[16];
    for (int i = 0; i < 16; ++i) M[i] = load_le32(blk + 4 * i);
    uint32_t a = st[0], b = st[1], c = st[2], d = st[3];

    for (int i = 0; i < 64; ++i) {
        uint32_t f;
        int g;
        if (i < 16)      { f = (b & c) | (~b & d); g = i; }
        else if (i < 32) { f = (d & b) | (~d & c); g = (5 * i + 1) & 15; }
        else if (i < 48) { f = b ^ c ^ d;          g = (3 * i + 5) & 15; }
        else             { f = c ^ (b | ~d);       g = (7 * i) & 15; }
        uint32_t t = d;
        d = c;
        c = b;
        b = b + rotl32(a + f + K[i] + M[g], S[i]);
        a = t;
    }
    st[0] += a; st[1] += b; st[2] += c; st[3] += d;
}

} // namespace

std::vector<uint8_t> netplus::md4_hash(const std::vector<uint8_t> &input) {
    return md_frame(input, md4_compress);
}

std::vector<uint8_t> netplus::md5_hash(const std::vector<uint8_t> &input) {
    return md_frame(input, md5_compress);
}

std::vector<uint8_t> netplus::hmac_md5(const std::vector<uint8_t> &key,
                                       const std::vector<uint8_t> &msg) {
    std::vector<uint8_t> k = key.size() > 64 ? md5_hash(key) : key;
    k.resize(64, 0);

    std::vector<uint8_t> inner(64 + msg.size());
    for (int i = 0; i < 64; ++i) inner[i] = k[i] ^ 0x36;
    if (!msg.empty()) std::memcpy(inner.data() + 64, msg.data(), msg.size());
    std::vector<uint8_t> ih = md5_hash(inner);

    std::vector<uint8_t> outer(64 + 16);
    for (int i = 0; i < 64; ++i) outer[i] = k[i] ^ 0x5c;
    std::memcpy(outer.data() + 64, ih.data(), 16);
    return md5_hash(outer);
}

bool netplus::hmac_md5_verify(const std::vector<uint8_t> &key,
                              const std::vector<uint8_t> &msg,
                              const std::vector<uint8_t> &mac) {
    std::vector<uint8_t> calc = hmac_md5(key, msg);
    if (mac.size() != calc.size()) return false;
    uint8_t diff = 0;
    for (size_t i = 0; i < calc.size(); ++i) diff |= (uint8_t)(calc[i] ^ mac[i]);
    return diff == 0;
}

src/crypto/md.h

0 → 100644
+49 −0
Changes for src/crypto/md.h: 49 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2026, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <cstdint>
#include <vector>

#pragma once

// MD4 (RFC 1320) and MD5 (RFC 1321) plus HMAC-MD5 (RFC 2104).
//
// Both digests are cryptographically broken and must NOT be used for anything new. They
// exist here solely for legacy protocol interop that has no alternative: NTLM (the NT hash
// is MD4(UTF-16LE(password)), NTLMv2 responses are HMAC-MD5 keyed by it -- needed for
// Microsoft Exchange IMAP/SMTP AUTH=NTLM), CRAM-MD5 SASL, and APOP.
namespace netplus {
    extern std::vector<uint8_t> md4_hash(const std::vector<uint8_t>& input);
    extern std::vector<uint8_t> md5_hash(const std::vector<uint8_t>& input);

    extern std::vector<uint8_t> hmac_md5(const std::vector<uint8_t>& key,
                                         const std::vector<uint8_t>& msg);
    // Constant-time comparison of hmac_md5(key,msg) against mac.
    extern bool hmac_md5_verify(const std::vector<uint8_t>& key,
                                const std::vector<uint8_t>& msg,
                                const std::vector<uint8_t>& mac);
} // namespace netplus
+9 −0
Changes for test/CMakeLists.txt: 9 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -36,6 +36,10 @@ add_executable(sha_nist sha_nist.cpp)

target_link_libraries(sha_nist netplus-static)

add_executable(md_test md_test.cpp)

target_link_libraries(md_test netplus-static)

add_executable(hmac_sha384 hmac_sha384.cpp)

target_link_libraries(hmac_sha384 netplus-static)
@@ -73,6 +77,11 @@ add_test(
    COMMAND sha_nist
)

add_test(
    NAME md_test
    COMMAND md_test
)

add_test(
    NAME hmac_sha384_test
    COMMAND hmac_sha384

test/md_test.cpp

0 → 100644
+70 −0
Changes for test/md_test.cpp: 70 added lines, 0 removed lines.
Original line number Diff line number Diff line
// MD4 (RFC 1320 A.5), MD5 (RFC 1321 A.5) and HMAC-MD5 (RFC 2202 section 2) test vectors.

#include <cstdio>
#include <string>
#include <vector>

#include "../src/crypto/md.h"

static std::string hex(const std::vector<uint8_t> &v) {
    std::string r;
    char b[3];
    for (uint8_t c : v) { snprintf(b, sizeof(b), "%02x", c); r += b; }
    return r;
}

static std::vector<uint8_t> bytes(const std::string &s) { return {s.begin(), s.end()}; }

static int failures = 0;

static void check(const char *what, const std::string &got, const std::string &want) {
    if (got != want) {
        printf("FAIL %s\n  got  %s\n  want %s\n", what, got.c_str(), want.c_str());
        ++failures;
    } else {
        printf("ok   %s\n", what);
    }
}

int main() {
    struct V { const char *in, *md4, *md5; };
    const V v[] = {
        {"", "31d6cfe0d16ae931b73c59d7e0c089c0", "d41d8cd98f00b204e9800998ecf8427e"},
        {"a", "bde52cb31de33e46245e05fbdbd6fb24", "0cc175b9c0f1b6a831c399e269772661"},
        {"abc", "a448017aaf21d8525fc10ae87aa6729d", "900150983cd24fb0d6963f7d28e17f72"},
        {"message digest", "d9130a8164549fe818874806e1c7014b", "f96b697d7cb7938d525a2f31aaf161d0"},
        {"abcdefghijklmnopqrstuvwxyz", "d79e1c308aa5bbcdeea8ed63df412da9", "c3fcd3d76192e4007dfb496cca67e13b"},
        {"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
         "043f8582f241db351ce627e153e7f0e4", "d174ab98d277d9f5a5611c2c9f419d9f"},
        {"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
         "e33b4ddc9c38f2199c3e7b164fcc0536", "57edf4a22be3c955ac49da2e2107b67a"},
    };
    for (const auto &t : v) {
        std::string label = std::string("\"") + t.in + "\"";
        check(("md4 " + label).c_str(), hex(netplus::md4_hash(bytes(t.in))), t.md4);
        check(("md5 " + label).c_str(), hex(netplus::md5_hash(bytes(t.in))), t.md5);
    }

    // RFC 2202 HMAC-MD5 cases 1, 2, 3, 6 (6 = key longer than block size).
    check("hmac_md5 #1", hex(netplus::hmac_md5(std::vector<uint8_t>(16, 0x0b), bytes("Hi There"))),
          "9294727a3638bb1c13f48ef8158bfc9d");
    check("hmac_md5 #2", hex(netplus::hmac_md5(bytes("Jefe"), bytes("what do ya want for nothing?"))),
          "750c783e6ab0b503eaa86e310a5db738");
    check("hmac_md5 #3", hex(netplus::hmac_md5(std::vector<uint8_t>(16, 0xaa), std::vector<uint8_t>(50, 0xdd))),
          "56be34521d144c88dbb8c733f0e8b3f6");
    check("hmac_md5 #6", hex(netplus::hmac_md5(std::vector<uint8_t>(80, 0xaa),
                                               bytes("Test Using Larger Than Block-Size Key - Hash Key First"))),
          "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd");

    auto mac = netplus::hmac_md5(bytes("Jefe"), bytes("what do ya want for nothing?"));
    if (!netplus::hmac_md5_verify(bytes("Jefe"), bytes("what do ya want for nothing?"), mac)) {
        printf("FAIL hmac_md5_verify accept\n"); ++failures;
    }
    mac[0] ^= 1;
    if (netplus::hmac_md5_verify(bytes("Jefe"), bytes("what do ya want for nothing?"), mac)) {
        printf("FAIL hmac_md5_verify reject\n"); ++failures;
    }

    printf("%s (%d failures)\n", failures ? "FAILED" : "PASSED", failures);
    return failures ? 1 : 0;
}