// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The User-based Security Model: RFC 3414, with RFC 3826's AES and RFC //! 7860's SHA-2 protocols. //! //! This is what SNMPv3 is *for*. Versions 1 and 2c authenticate with a //! community string sent in the clear, which is to say they do not //! authenticate at all; USM replaces that with an HMAC over the whole message //! and, optionally, encryption of the part that says anything. //! //! ## The password is not the key //! //! Two derivations stand between a password and what actually signs a //! message, and both matter. //! //! `passwordToKey` (RFC 3414 §A.2.1) hashes the password **repeated to fill //! exactly 1,048,576 octets**. That megabyte is not decoration: it makes a //! dictionary attack a megabyte of hashing per candidate instead of one block, //! which in 1998 was the difference between minutes and months. It is also //! why deriving a key is visibly slow, and why `Client` does it once per user //! and caches the result. //! //! `localizeKey` then binds that key to one agent by hashing //! `Ku || engineID || Ku`. The point is compartmentalisation: the same //! password at fifty devices yields fifty unrelated keys, so a key recovered //! from one device does not open the other forty-nine. It also means a client //! cannot compute its keys until it knows who it is talking to, which is what //! engine discovery is for. //! //! ## Where the truncation lengths come from //! //! An HMAC is computed at the hash's full width and then **truncated**, and //! each protocol truncates differently: 12 octets for the two RFC 3414 //! protocols, and 16, 24, 32 and 48 for the RFC 7860 ones. That is what the //! `_96` and `_192` suffixes in the protocol names count -- bits. Getting one //! wrong produces a client that authenticates against nothing, and net-snmp //! reports it as "Authentication failure (incorrect password, community or //! key)" with no hint as to which, so each one is its own test here. const std = @import("std"); const Io = std.Io; const assert = std.debug.assert; const testing = std.testing; /// The ciphers and modes `std.crypto` leaves out. Imported as `des` because /// that is what most of the uses below are, though it also supplies the /// AES-192 that `std` has no key schedule for. const des = @import("std_crypto_ext"); /// How a message is authenticated. pub const AuthProtocol = enum { none, /// RFC 3414 §6. `usmHMACMD5AuthProtocol`. hmac_md5_96, /// RFC 3414 §7. `usmHMACSHAAuthProtocol`. hmac_sha1_96, /// RFC 7860. The four SHA-2 protocols, which net-snmp 5.9 supports and /// a good deal of older equipment does not. hmac_sha224_128, hmac_sha256_192, hmac_sha384_256, hmac_sha512_384, /// The length of a derived key, which is the hash's full digest length. pub fn keyLength(a: AuthProtocol) usize { return switch (a) { .none => 0, .hmac_md5_96 => 16, .hmac_sha1_96 => 20, .hmac_sha224_128 => 28, .hmac_sha256_192 => 32, .hmac_sha384_256 => 48, .hmac_sha512_384 => 64, }; } /// How many octets of the HMAC go in the message. This is the number in /// the protocol's name, in octets rather than bits. pub fn digestLength(a: AuthProtocol) usize { return switch (a) { .none => 0, .hmac_md5_96, .hmac_sha1_96 => 12, .hmac_sha224_128 => 16, .hmac_sha256_192 => 24, .hmac_sha384_256 => 32, .hmac_sha512_384 => 48, }; } /// The longest `digestLength` any protocol here has, for sizing a buffer. pub const max_digest_length = 48; /// And the longest key. pub const max_key_length = 64; /// As net-snmp spells it after `-a`. pub fn parse(text: []const u8) ?AuthProtocol { const table = .{ .{ "MD5", AuthProtocol.hmac_md5_96 }, .{ "SHA", AuthProtocol.hmac_sha1_96 }, .{ "SHA-1", AuthProtocol.hmac_sha1_96 }, .{ "SHA1", AuthProtocol.hmac_sha1_96 }, .{ "SHA-224", AuthProtocol.hmac_sha224_128 }, .{ "SHA-256", AuthProtocol.hmac_sha256_192 }, .{ "SHA-384", AuthProtocol.hmac_sha384_256 }, .{ "SHA-512", AuthProtocol.hmac_sha512_384 }, .{ "SHA224", AuthProtocol.hmac_sha224_128 }, .{ "SHA256", AuthProtocol.hmac_sha256_192 }, .{ "SHA384", AuthProtocol.hmac_sha384_256 }, .{ "SHA512", AuthProtocol.hmac_sha512_384 }, }; inline for (table) |entry| { if (std.ascii.eqlIgnoreCase(text, entry[0])) return entry[1]; } return null; } pub fn name(a: AuthProtocol) []const u8 { return switch (a) { .none => "none", .hmac_md5_96 => "MD5", .hmac_sha1_96 => "SHA", .hmac_sha224_128 => "SHA-224", .hmac_sha256_192 => "SHA-256", .hmac_sha384_256 => "SHA-384", .hmac_sha512_384 => "SHA-512", }; } }; /// How the scoped PDU is encrypted. pub const PrivProtocol = enum { none, /// RFC 3414 §8: DES in CBC mode. Obsolete and still the default on a /// great deal of network equipment, which is the whole reason `zig-des` /// exists. des_cbc, /// Triple DES in EDE CBC, from draft-reeder-snmpv3-usm-3desede. /// /// **Not a standard either.** That draft expired, and net-snmp 5.9's /// command line refuses the protocol. Cisco IOS implements it, which is /// the only reason this is here. /// /// It takes 32 octets of localized key -- 24 for the three DES keys and /// eight for the pre-IV -- where MD5's derivation produces 16, so it is /// the protocol `extendKey` was written for in the first place: the draft /// that defines the chaining is the same one that defines this. des3_cbc, /// RFC 3826: AES-128 in full-block CFB. aes_128_cfb, /// AES-192 in full-block CFB, from draft-blumenthal-aes-usm. The cipher /// comes from `zig-des`, because `std.crypto` has no AES-192. aes_192_cfb, /// AES-256 in full-block CFB, from draft-blumenthal-aes-usm. /// /// **Not a standard.** That draft expired without becoming an RFC, and /// net-snmp 5.9's command line will not speak it even though its library /// implements the key extension. Cisco IOS does, which is the only reason /// this is here and the only thing it can be checked against. /// /// It needs 32 octets of localized key where SHA-1's derivation produces /// 20, so it is also the reason `extendKey` exists. aes_256_cfb, /// The localized key material this protocol consumes. /// /// DES and AES-128 both take 16 octets, though they use them differently: /// DES uses the first eight as key and the second eight as a pre-IV, /// while AES-128 uses all sixteen as key. pub fn keyLength(p: PrivProtocol) usize { return switch (p) { .none => 0, .des_cbc, .aes_128_cfb => 16, .aes_192_cfb => 24, .des3_cbc, .aes_256_cfb => 32, }; } /// The longest key any protocol here needs, for sizing a buffer. pub const max_key_length = 32; /// As net-snmp spells it after `-x`. pub fn parse(text: []const u8) ?PrivProtocol { if (std.ascii.eqlIgnoreCase(text, "DES")) return .des_cbc; if (std.ascii.eqlIgnoreCase(text, "3DES")) return .des3_cbc; if (std.ascii.eqlIgnoreCase(text, "3DESEDE")) return .des3_cbc; if (std.ascii.eqlIgnoreCase(text, "DES3")) return .des3_cbc; if (std.ascii.eqlIgnoreCase(text, "AES")) return .aes_128_cfb; if (std.ascii.eqlIgnoreCase(text, "AES-128")) return .aes_128_cfb; if (std.ascii.eqlIgnoreCase(text, "AES128")) return .aes_128_cfb; // Cisco spells these with and without the dash, and net-snmp's // Blumenthal patch adds a `-C` suffix for the Cisco key extension. if (std.ascii.eqlIgnoreCase(text, "AES-192")) return .aes_192_cfb; if (std.ascii.eqlIgnoreCase(text, "AES192")) return .aes_192_cfb; if (std.ascii.eqlIgnoreCase(text, "AES-192-C")) return .aes_192_cfb; if (std.ascii.eqlIgnoreCase(text, "AES-256")) return .aes_256_cfb; if (std.ascii.eqlIgnoreCase(text, "AES256")) return .aes_256_cfb; if (std.ascii.eqlIgnoreCase(text, "AES-256-C")) return .aes_256_cfb; return null; } pub fn name(p: PrivProtocol) []const u8 { return switch (p) { .none => "none", .des_cbc => "DES", .des3_cbc => "3DES", .aes_128_cfb => "AES", .aes_192_cfb => "AES-192", .aes_256_cfb => "AES-256", }; } }; /// What RFC 3411 calls the security level: how much of USM is being used. pub const SecurityLevel = enum { /// A name and nothing else, which is what engine discovery uses. no_auth_no_priv, /// Authenticated, and readable by anybody on the wire. auth_no_priv, /// Authenticated and encrypted. auth_priv, /// The two bits of `msgFlags` this occupies. The third bit is /// `reportable` and is not part of the level. pub fn flags(l: SecurityLevel) u8 { return switch (l) { .no_auth_no_priv => 0x00, .auth_no_priv => 0x01, .auth_priv => 0x03, }; } /// As net-snmp spells it after `-l`. pub fn parse(text: []const u8) ?SecurityLevel { if (std.ascii.eqlIgnoreCase(text, "noAuthNoPriv")) return .no_auth_no_priv; if (std.ascii.eqlIgnoreCase(text, "authNoPriv")) return .auth_no_priv; if (std.ascii.eqlIgnoreCase(text, "authPriv")) return .auth_priv; // net-snmp accepts these abbreviations too. if (std.ascii.eqlIgnoreCase(text, "noauth")) return .no_auth_no_priv; if (std.ascii.eqlIgnoreCase(text, "auth")) return .auth_no_priv; if (std.ascii.eqlIgnoreCase(text, "priv")) return .auth_priv; return null; } pub fn name(l: SecurityLevel) []const u8 { return switch (l) { .no_auth_no_priv => "noAuthNoPriv", .auth_no_priv => "authNoPriv", .auth_priv => "authPriv", }; } }; /// How many octets of the password are hashed: exactly one mebibyte. /// /// The number is in RFC 3414 §A.2.1 and is the whole of the algorithm's /// resistance to a dictionary attack. pub const password_expansion = 1024 * 1024; /// RFC 3414 §A.2.1: the key a password yields, before it is bound to any /// agent. /// /// `out` must be exactly `protocol.keyLength()`. This hashes a megabyte and /// so takes a few milliseconds; derive once and keep the answer. pub fn passwordToKey(protocol: AuthProtocol, password: []const u8, out: []u8) void { assert(out.len == protocol.keyLength()); assert(password.len > 0); switch (protocol) { .none => {}, .hmac_md5_96 => expand(std.crypto.hash.Md5, password, out), .hmac_sha1_96 => expand(std.crypto.hash.Sha1, password, out), .hmac_sha224_128 => expand(std.crypto.hash.sha2.Sha224, password, out), .hmac_sha256_192 => expand(std.crypto.hash.sha2.Sha256, password, out), .hmac_sha384_256 => expand(std.crypto.hash.sha2.Sha384, password, out), .hmac_sha512_384 => expand(std.crypto.hash.sha2.Sha512, password, out), } } fn expand(comptime Hash: type, password: []const u8, out: []u8) void { var hash: Hash = .init(.{}); // The password repeated, in chunks, with the index carried across chunk // boundaries -- so what is hashed is the first megabyte of the password // repeated end to end, not a megabyte of whole copies. A reading that // restarts the password at each chunk gives a different key for any // password whose length does not divide the chunk size, and the RFC's own // C code makes this easy to get wrong. var buffer: [64]u8 = undefined; var index: usize = 0; var written: usize = 0; while (written < password_expansion) : (written += buffer.len) { for (&buffer) |*byte| { byte.* = password[index % password.len]; index += 1; } hash.update(&buffer); } var digest: [Hash.digest_length]u8 = undefined; hash.final(&digest); @memcpy(out, digest[0..out.len]); } /// RFC 3414 §2.6: the key bound to one agent, `H(Ku || engineID || Ku)`. /// /// This is why the same password at fifty devices is fifty unrelated keys, /// and why a client cannot compute anything until engine discovery has told /// it who it is talking to. pub fn localizeKey( protocol: AuthProtocol, key: []const u8, engine_id: []const u8, out: []u8, ) void { assert(key.len == protocol.keyLength()); assert(out.len == protocol.keyLength()); switch (protocol) { .none => {}, .hmac_md5_96 => localize(std.crypto.hash.Md5, key, engine_id, out), .hmac_sha1_96 => localize(std.crypto.hash.Sha1, key, engine_id, out), .hmac_sha224_128 => localize(std.crypto.hash.sha2.Sha224, key, engine_id, out), .hmac_sha256_192 => localize(std.crypto.hash.sha2.Sha256, key, engine_id, out), .hmac_sha384_256 => localize(std.crypto.hash.sha2.Sha384, key, engine_id, out), .hmac_sha512_384 => localize(std.crypto.hash.sha2.Sha512, key, engine_id, out), } } fn localize(comptime Hash: type, key: []const u8, engine_id: []const u8, out: []u8) void { var hash: Hash = .init(.{}); hash.update(key); hash.update(engine_id); hash.update(key); var digest: [Hash.digest_length]u8 = undefined; hash.final(&digest); @memcpy(out, digest[0..out.len]); } /// How a localized key is made longer than the hash that produced it. /// /// SHA-1's derivation yields 20 octets and AES-256 needs 32, so something has /// to stretch it -- and the something is not standardised. The method below is /// the one draft-reeder-snmpv3-usm-3desede describes and that net-snmp /// implements as `netsnmp_extend_kul`: chain the derivation, feeding each /// localized key back in as though it were the password. /// /// Each additional chunk therefore costs another megabyte of hashing, which /// is why this is done once per user and engine and cached. pub fn extendKey( protocol: AuthProtocol, password: []const u8, engine_id: []const u8, out: []u8, ) void { const chunk = protocol.keyLength(); assert(chunk > 0); var ku: [AuthProtocol.max_key_length]u8 = undefined; passwordToKey(protocol, password, ku[0..chunk]); var kul: [AuthProtocol.max_key_length]u8 = undefined; localizeKey(protocol, ku[0..chunk], engine_id, kul[0..chunk]); var written: usize = 0; while (written < out.len) { const take = @min(chunk, out.len - written); @memcpy(out[written..][0..take], kul[0..take]); written += take; if (written >= out.len) break; // The chain: the localized key just produced becomes the input to the // next derivation, as though it were the password. Note it is the // *localized* key that is fed back, not the unlocalized one -- which // is the detail that makes the extension engine-specific all the way // down. var next_ku: [AuthProtocol.max_key_length]u8 = undefined; passwordToKey(protocol, kul[0..chunk], next_ku[0..chunk]); localizeKey(protocol, next_ku[0..chunk], engine_id, kul[0..chunk]); } } /// The privacy key. /// /// When the protocol needs no more than the hash produces, this is the /// authentication derivation **truncated** -- which is worth noticing: with /// SHA-512 the authentication key is 64 octets and an AES-128 privacy key is /// the first 16 of the same derivation, so a stronger hash buys no extra /// privacy key material at all. RFC 3826 §3.1.2.1 says so and RFC 7860 keeps /// it. /// /// When the protocol needs *more* -- AES-256 wants 32 octets and SHA-1 gives /// 20 -- the key is extended instead. That case is not standardised; see /// `extendKey`. pub fn privacyKey( protocol: AuthProtocol, priv: PrivProtocol, password: []const u8, engine_id: []const u8, out: []u8, ) void { assert(out.len == priv.keyLength()); if (out.len > protocol.keyLength()) { extendKey(protocol, password, engine_id, out); return; } var full: [AuthProtocol.max_key_length]u8 = undefined; const key = full[0..protocol.keyLength()]; passwordToKey(protocol, password, key); var localized: [AuthProtocol.max_key_length]u8 = undefined; const bound = localized[0..protocol.keyLength()]; localizeKey(protocol, key, engine_id, bound); @memcpy(out, bound[0..out.len]); } /// The HMAC over a whole message, truncated to the protocol's length. /// /// `message` is the complete BER encoding with the authentication parameters /// field present and **zeroed**: RFC 3414 §6.3.1 computes the digest over the /// message that will contain it, so the field is written as the right number /// of zero octets, the digest taken over everything, and the zeroes then /// replaced. That is why `asn1.Encoder.contentOffset` exists. pub fn authenticate( protocol: AuthProtocol, localized_key: []const u8, message: []const u8, out: []u8, ) void { assert(out.len == protocol.digestLength()); const hmac = std.crypto.auth.hmac; switch (protocol) { .none => {}, .hmac_md5_96 => mac(hmac.HmacMd5, localized_key, message, out), .hmac_sha1_96 => mac(hmac.HmacSha1, localized_key, message, out), .hmac_sha224_128 => mac(hmac.sha2.HmacSha224, localized_key, message, out), .hmac_sha256_192 => mac(hmac.sha2.HmacSha256, localized_key, message, out), .hmac_sha384_256 => mac(hmac.sha2.HmacSha384, localized_key, message, out), .hmac_sha512_384 => mac(hmac.sha2.HmacSha512, localized_key, message, out), } } fn mac(comptime Hmac: type, key: []const u8, message: []const u8, out: []u8) void { var full: [Hmac.mac_length]u8 = undefined; Hmac.create(&full, message, key); @memcpy(out, full[0..out.len]); } /// Whether `expected` is the digest of `message`, compared in constant time. /// /// The comparison has to be constant time because an attacker who can measure /// how long a rejection took can otherwise recover a valid digest one octet /// at a time -- the classic MAC-comparison timing attack, and a plain /// `mem.eql` is exactly how it happens. pub fn verify( protocol: AuthProtocol, localized_key: []const u8, message: []const u8, expected: []const u8, ) bool { if (protocol == .none) return true; if (expected.len != protocol.digestLength()) return false; var computed: [AuthProtocol.max_digest_length]u8 = undefined; const digest = computed[0..protocol.digestLength()]; authenticate(protocol, localized_key, message, digest); return std.crypto.timing_safe.eql([AuthProtocol.max_digest_length]u8, blk: { var padded: [AuthProtocol.max_digest_length]u8 = @splat(0); @memcpy(padded[0..digest.len], digest); break :blk padded; }, blk: { var padded: [AuthProtocol.max_digest_length]u8 = @splat(0); @memcpy(padded[0..expected.len], expected); break :blk padded; }); } // -- privacy ---------------------------------------------------------------- /// The salt a privacy protocol puts in `msgPrivacyParameters`, and the IV it /// builds from it. pub const Salt = struct { /// What goes on the wire: eight octets for both protocols, though they /// mean different things. bytes: [8]u8, pub const length = 8; }; /// DES-CBC, RFC 3414 §8.1.1. /// /// The key is the first eight octets of the localized privacy key and the /// remaining eight are the **pre-IV** -- not key material at all, which is /// the part that surprises people. The salt on the wire is the engine boots /// and a counter, and the actual IV is that salt XORed with the pre-IV. /// /// So a 16-octet localized key yields a 56-bit effective key, which is the /// other reason not to choose this. pub const Des = struct { pub fn salt(engine_boots: u32, counter: u32) Salt { var out: Salt = .{ .bytes = undefined }; std.mem.writeInt(u32, out.bytes[0..4], engine_boots, .big); std.mem.writeInt(u32, out.bytes[4..8], counter, .big); return out; } fn iv(privacy_key: []const u8, s: Salt) [8]u8 { assert(privacy_key.len >= 16); var out: [8]u8 = undefined; for (&out, privacy_key[8..16], s.bytes) |*byte, pre, salt_byte| { byte.* = pre ^ salt_byte; } return out; } /// Encrypts in place-compatible fashion into `out`, which must be /// `paddedLength(plaintext.len)` long. Returns the ciphertext. /// /// CBC needs whole blocks, and RFC 3414 §8.1.1.2 says to pad with /// whatever is convenient -- the receiver finds the real end from the BER /// length inside the plaintext rather than from a padding scheme. Zeroes /// are as convenient as anything. pub fn encrypt(privacy_key: []const u8, s: Salt, plaintext: []const u8, out: []u8) []u8 { const padded = paddedLength(plaintext.len); assert(out.len >= padded); @memcpy(out[0..plaintext.len], plaintext); @memset(out[plaintext.len..padded], 0); des.modes.cbcEncrypt( des.Des.EncryptCtx, des.Des.initEnc(privacy_key[0..8].*), out[0..padded], out[0..padded], iv(privacy_key, s), ); return out[0..padded]; } pub const DecryptError = error{ /// The ciphertext is not a whole number of blocks, so it was not /// produced by this mode. NotBlockAligned, }; pub fn decrypt(privacy_key: []const u8, s: Salt, ciphertext: []const u8, out: []u8) DecryptError![]u8 { if (ciphertext.len == 0 or ciphertext.len % 8 != 0) return error.NotBlockAligned; assert(out.len >= ciphertext.len); des.modes.cbcDecrypt( des.Des.DecryptCtx, des.Des.initDec(privacy_key[0..8].*), out[0..ciphertext.len], ciphertext, iv(privacy_key, s), ); return out[0..ciphertext.len]; } pub fn paddedLength(len: usize) usize { return (len + 7) / 8 * 8; } }; /// Triple DES in EDE CBC, draft-reeder-snmpv3-usm-3desede. /// /// Laid out exactly as single DES is, only wider: the localized key is 32 /// octets, of which the first 24 are the three DES keys and the last eight /// are the **pre-IV** rather than key material. The salt on the wire is the /// engine boots and a counter, and the IV is that salt XORed with the pre-IV /// -- identical to `Des`, which is the point of the design: a implementation /// that already did DES had only to widen the key. /// /// Two-key 3DES would be this with K3 equal to K1. The draft specifies the /// three-key form, and the key extension supplies enough material for it, so /// that is what this does. pub const Des3 = struct { /// Where the key stops and the pre-IV begins. pub const key_octets = 24; pub fn salt(engine_boots: u32, counter: u32) Salt { // The same construction as single DES, deliberately. return Des.salt(engine_boots, counter); } fn iv(privacy_key: []const u8, s: Salt) [8]u8 { assert(privacy_key.len >= 32); var out: [8]u8 = undefined; for (&out, privacy_key[24..32], s.bytes) |*byte, pre, salt_byte| { byte.* = pre ^ salt_byte; } return out; } pub fn encrypt(privacy_key: []const u8, s: Salt, plaintext: []const u8, out: []u8) []u8 { const padded = Des.paddedLength(plaintext.len); assert(out.len >= padded); @memcpy(out[0..plaintext.len], plaintext); @memset(out[plaintext.len..padded], 0); des.modes.cbcEncrypt( des.Des3.EncryptCtx, des.Des3.initEnc(privacy_key[0..key_octets].*), out[0..padded], out[0..padded], iv(privacy_key, s), ); return out[0..padded]; } pub fn decrypt( privacy_key: []const u8, s: Salt, ciphertext: []const u8, out: []u8, ) Des.DecryptError![]u8 { if (ciphertext.len == 0 or ciphertext.len % 8 != 0) return error.NotBlockAligned; assert(out.len >= ciphertext.len); des.modes.cbcDecrypt( des.Des3.DecryptCtx, des.Des3.initDec(privacy_key[0..key_octets].*), out[0..ciphertext.len], ciphertext, iv(privacy_key, s), ); return out[0..ciphertext.len]; } }; /// AES-128 in full-block CFB, RFC 3826 §3.1. /// /// Unlike DES this needs no padding -- CFB is a stream mode -- and the whole /// 16-octet localized key is key material. The IV is /// `engineBoots || engineTime || salt`, which is 4 + 4 + 8 = 16 octets, so the /// IV depends on the agent's notion of time and a receiver that has /// resynchronized will build a different one. pub const Aes = struct { const aes = std.crypto.core.aes; const Aes128 = aes.Aes128; const Aes256 = aes.Aes256; const AesEncryptCtx = aes.AesEncryptCtx; /// From `zig-des` rather than `std`, which has no AES-192. const Aes192 = des.Aes192; /// A salt that must never repeat under one key. A counter is what RFC /// 3826 §3.3.1 suggests, seeded unpredictably. pub fn salt(counter: u64) Salt { var out: Salt = .{ .bytes = undefined }; std.mem.writeInt(u64, &out.bytes, counter, .big); return out; } fn iv(engine_boots: u32, engine_time: u32, s: Salt) [16]u8 { var out: [16]u8 = undefined; std.mem.writeInt(u32, out[0..4], engine_boots, .big); std.mem.writeInt(u32, out[4..8], engine_time, .big); @memcpy(out[8..16], &s.bytes); return out; } /// The IV construction is the same whatever the key length -- 16 octets /// of boots, time and salt -- so the only thing that varies is the key /// schedule. CFB is a stream mode, so neither length needs padding. pub fn encrypt( privacy_key: []const u8, engine_boots: u32, engine_time: u32, s: Salt, plaintext: []const u8, out: []u8, ) []u8 { assert(out.len >= plaintext.len); const vector = iv(engine_boots, engine_time, s); switch (privacy_key.len) { 16 => des.modes.cfbEncrypt( AesEncryptCtx(Aes128), Aes128.initEnc(privacy_key[0..16].*), out[0..plaintext.len], plaintext, vector, ), 24 => des.modes.cfbEncrypt( Aes192.EncryptCtx, Aes192.initEnc(privacy_key[0..24].*), out[0..plaintext.len], plaintext, vector, ), 32 => des.modes.cfbEncrypt( AesEncryptCtx(Aes256), Aes256.initEnc(privacy_key[0..32].*), out[0..plaintext.len], plaintext, vector, ), else => unreachable, } return out[0..plaintext.len]; } pub fn decrypt( privacy_key: []const u8, engine_boots: u32, engine_time: u32, s: Salt, ciphertext: []const u8, out: []u8, ) []u8 { assert(out.len >= ciphertext.len); const vector = iv(engine_boots, engine_time, s); // An *encryption* context, in both directions: CFB only ever runs the // cipher forwards. switch (privacy_key.len) { 16 => des.modes.cfbDecrypt( AesEncryptCtx(Aes128), Aes128.initEnc(privacy_key[0..16].*), out[0..ciphertext.len], ciphertext, vector, ), 24 => des.modes.cfbDecrypt( Aes192.EncryptCtx, Aes192.initEnc(privacy_key[0..24].*), out[0..ciphertext.len], ciphertext, vector, ), 32 => des.modes.cfbDecrypt( AesEncryptCtx(Aes256), Aes256.initEnc(privacy_key[0..32].*), out[0..ciphertext.len], ciphertext, vector, ), else => unreachable, } return out[0..ciphertext.len]; } }; /// Everything needed to speak as one user to one agent. pub const User = struct { name: []const u8, level: SecurityLevel = .no_auth_no_priv, auth: AuthProtocol = .none, priv: PrivProtocol = .none, auth_password: []const u8 = "", priv_password: []const u8 = "", /// Whether the level and the protocols agree. A level asking for /// authentication with no protocol chosen is a configuration mistake that /// would otherwise show up as an unexplained rejection. pub fn isConsistent(u: User) bool { if (u.name.len == 0) return false; return switch (u.level) { .no_auth_no_priv => true, .auth_no_priv => u.auth != .none and u.auth_password.len > 0, .auth_priv => u.auth != .none and u.auth_password.len > 0 and u.priv != .none and u.priv_password.len > 0, }; } }; /// The keys a user has for one agent, derived once and kept. /// /// Derivation costs a megabyte of hashing per key, so a client that re-derived /// per request would spend more time on that than on the network. pub const Keys = struct { auth: [AuthProtocol.max_key_length]u8 = @splat(0), auth_len: usize = 0, priv: [PrivProtocol.max_key_length]u8 = @splat(0), priv_len: usize = 0, pub fn derive(user: User, engine_id: []const u8) Keys { var keys: Keys = .{}; if (user.auth == .none) return keys; keys.auth_len = user.auth.keyLength(); var ku: [AuthProtocol.max_key_length]u8 = undefined; passwordToKey(user.auth, user.auth_password, ku[0..keys.auth_len]); localizeKey(user.auth, ku[0..keys.auth_len], engine_id, keys.auth[0..keys.auth_len]); if (user.priv != .none) { keys.priv_len = user.priv.keyLength(); privacyKey( user.auth, user.priv, user.priv_password, engine_id, keys.priv[0..keys.priv_len], ); } return keys; } pub fn authKey(k: *const Keys) []const u8 { return k.auth[0..k.auth_len]; } pub fn privKey(k: *const Keys) []const u8 { return k.priv[0..k.priv_len]; } }; // -- tests ------------------------------------------------------------------ /// The engine ID from RFC 3414 §A.3, so that the vectors below are the /// published ones. const rfc3414_engine_id = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2 }; fn expectKeys( protocol: AuthProtocol, password: []const u8, expected_ku: []const u8, expected_kul: []const u8, ) !void { var ku: [AuthProtocol.max_key_length]u8 = undefined; const key = ku[0..protocol.keyLength()]; passwordToKey(protocol, password, key); try testing.expectEqualSlices(u8, expected_ku, key); var kul: [AuthProtocol.max_key_length]u8 = undefined; const bound = kul[0..protocol.keyLength()]; localizeKey(protocol, key, &rfc3414_engine_id, bound); try testing.expectEqualSlices(u8, expected_kul, bound); } test "RFC 3414 A.3.1: the MD5 key for maplesyrup" { // The published vector, verbatim from the RFC. This is the one number in // the whole of USM that everybody checks first. try expectKeys( .hmac_md5_96, "maplesyrup", &.{ 0x9f, 0xaf, 0x32, 0x83, 0x88, 0x4e, 0x92, 0x83, 0x4e, 0xbc, 0x98, 0x47, 0xd8, 0xed, 0xd9, 0x63 }, &.{ 0x52, 0x6f, 0x5e, 0xed, 0x9f, 0xcc, 0xe2, 0x6f, 0x89, 0x64, 0xc2, 0x93, 0x07, 0x87, 0xd8, 0x2b }, ); } test "RFC 3414 A.3.2: the SHA-1 key for maplesyrup" { try expectKeys( .hmac_sha1_96, "maplesyrup", &.{ 0x9f, 0xb5, 0xcc, 0x03, 0x81, 0x49, 0x7b, 0x37, 0x93, 0x52, 0x89, 0x39, 0xff, 0x78, 0x8d, 0x5d, 0x79, 0x14, 0x52, 0x11, }, &.{ 0x66, 0x95, 0xfe, 0xbc, 0x92, 0x88, 0xe3, 0x62, 0x82, 0x23, 0x5f, 0xc7, 0x15, 0x1f, 0x12, 0x84, 0x97, 0xb3, 0x8f, 0x3f, }, ); } test "the SHA-2 keys for the same password" { // RFC 7860 publishes no vectors for these, so they were computed with an // independent implementation (Python's hashlib) whose agreement with the // two RFC 3414 vectors above was checked first. That is the same // discipline as the DES vectors in zig-des: a number somebody else // computed, not one this code produced. try expectKeys( .hmac_sha224_128, "maplesyrup", &.{ 0x28, 0x2a, 0x58, 0x67, 0xee, 0x9a, 0xac, 0x63, 0x9a, 0xd5, 0x9d, 0xf9, 0x57, 0x2c, 0x7d, 0x3a, 0xc0, 0xfb, 0xc1, 0x3a, 0x90, 0x5b, 0x6d, 0xf0, 0x7d, 0xbb, 0xf0, 0x0b, }, &.{ 0x0b, 0xd8, 0x82, 0x7c, 0x6e, 0x29, 0xf8, 0x06, 0x5e, 0x08, 0xe0, 0x92, 0x37, 0xf1, 0x77, 0xe4, 0x10, 0xf6, 0x9b, 0x90, 0xe1, 0x78, 0x2b, 0xe6, 0x82, 0x07, 0x56, 0x74, }, ); try expectKeys( .hmac_sha256_192, "maplesyrup", &.{ 0xab, 0x51, 0x01, 0x4d, 0x1e, 0x07, 0x7f, 0x60, 0x17, 0xdf, 0x2b, 0x12, 0xbe, 0xe5, 0xf5, 0xaa, 0x72, 0x99, 0x31, 0x77, 0xe9, 0xbb, 0x56, 0x9c, 0x4d, 0xff, 0x5a, 0x4c, 0xa0, 0xb4, 0xaf, 0xac, }, &.{ 0x89, 0x82, 0xe0, 0xe5, 0x49, 0xe8, 0x66, 0xdb, 0x36, 0x1a, 0x6b, 0x62, 0x5d, 0x84, 0xcc, 0xcc, 0x11, 0x16, 0x2d, 0x45, 0x3e, 0xe8, 0xce, 0x3a, 0x64, 0x45, 0xc2, 0xd6, 0x77, 0x6f, 0x0f, 0x8b, }, ); } test "a password of an awkward length, where the megabyte wraps mid-chunk" { // The expansion carries its index across 64-octet chunks, so a password // whose length does not divide 64 is the case that distinguishes a // correct implementation from one that restarts the password at every // chunk. Both give the same answer for a 64-octet password and different // answers for almost anything else, which is why this is here rather // than trusting the two vectors above -- "maplesyrup" is ten octets, so // it happens to cover it, and a regression could still slip past a test // suite with only round numbers in it. var key: [16]u8 = undefined; // One octet, which divides 64, so any reading agrees: MD5 of a mebibyte // of 'a'. passwordToKey(.hmac_md5_96, "a", &key); try testing.expectEqualSlices(u8, &.{ 0x72, 0x02, 0x82, 0x6a, 0x77, 0x91, 0x07, 0x3f, 0xe2, 0x78, 0x7f, 0x0c, 0x94, 0x60, 0x32, 0x78, }, &key); // Three octets, which does not divide 64 -- so a chunk boundary falls // mid-password and an implementation that restarted the password at each // chunk would differ here and nowhere above. passwordToKey(.hmac_md5_96, "abc", &key); try testing.expectEqualSlices(u8, &.{ 0x99, 0x2d, 0x2d, 0x55, 0x39, 0x2e, 0x20, 0x45, 0xee, 0x1e, 0x07, 0x11, 0xca, 0x73, 0xc6, 0xeb, }, &key); // And sixteen, which divides 64 again, to bracket the case. passwordToKey(.hmac_md5_96, "0123456789abcdef", &key); try testing.expectEqualSlices(u8, &.{ 0x14, 0xd7, 0x85, 0xda, 0xab, 0x38, 0x23, 0x73, 0x6c, 0x98, 0x1c, 0xa8, 0x2a, 0x75, 0x0c, 0x98, }, &key); } test "the key and digest lengths are the numbers in the protocols' names" { // Getting one of these wrong authenticates against nothing, and net-snmp // reports only "Authentication failure" with no hint which. const table = [_]struct { AuthProtocol, usize, usize }{ .{ .hmac_md5_96, 16, 12 }, .{ .hmac_sha1_96, 20, 12 }, .{ .hmac_sha224_128, 28, 16 }, .{ .hmac_sha256_192, 32, 24 }, .{ .hmac_sha384_256, 48, 32 }, .{ .hmac_sha512_384, 64, 48 }, }; for (table) |row| { try testing.expectEqual(row[1], row[0].keyLength()); try testing.expectEqual(row[2], row[0].digestLength()); // The suffix counts bits of digest, so it is eight times the octets. try testing.expect(row[0].digestLength() * 8 <= row[0].keyLength() * 8); try testing.expect(row[0].digestLength() <= AuthProtocol.max_digest_length); try testing.expect(row[0].keyLength() <= AuthProtocol.max_key_length); } } test "a digest verifies, and one octet off does not" { var keys = Keys.derive(.{ .name = "someone", .level = .auth_no_priv, .auth = .hmac_sha1_96, .auth_password = "maplesyrup", }, &rfc3414_engine_id); const message = "a message that will be authenticated"; var digest: [12]u8 = undefined; authenticate(.hmac_sha1_96, keys.authKey(), message, &digest); try testing.expect(verify(.hmac_sha1_96, keys.authKey(), message, &digest)); // Every single-bit change in the digest must fail. for (0..digest.len) |i| { var tampered = digest; tampered[i] ^= 1; try testing.expect(!verify(.hmac_sha1_96, keys.authKey(), message, &tampered)); } // A digest of the wrong length is not a near miss, it is malformed. try testing.expect(!verify(.hmac_sha1_96, keys.authKey(), message, digest[0..11])); // And a changed message fails with the right digest. try testing.expect(!verify(.hmac_sha1_96, keys.authKey(), "a different message", &digest)); } test "DES privacy round-trips, and its key is only eight octets" { const privacy_key = [_]u8{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, }; const s = Des.salt(1, 42); // The salt on the wire is the boots and the counter, in that order. try testing.expectEqualSlices(u8, &.{ 0, 0, 0, 1, 0, 0, 0, 42 }, &s.bytes); const plaintext = "a scoped PDU, more or less"; var buffer: [64]u8 = undefined; const ciphertext = Des.encrypt(&privacy_key, s, plaintext, &buffer); // Padded up to a block, because CBC cannot do a partial one. try testing.expectEqual(Des.paddedLength(plaintext.len), ciphertext.len); try testing.expectEqual(@as(usize, 0), ciphertext.len % 8); var back: [64]u8 = undefined; const decrypted = try Des.decrypt(&privacy_key, s, ciphertext, &back); // The padding comes back too: the receiver finds the real end from the // BER length inside, not from a padding scheme. try testing.expectEqualStrings(plaintext, decrypted[0..plaintext.len]); // Only the first eight octets are key; the rest is the pre-IV. So // changing the second half changes the IV and therefore the ciphertext, // and changing the first half changes the key. var other = privacy_key; other[8] ^= 0xff; var buffer2: [64]u8 = undefined; const different = Des.encrypt(&other, s, plaintext, &buffer2); try testing.expect(!std.mem.eql(u8, ciphertext, different)); // Ciphertext that is not whole blocks was not made by this mode. try testing.expectError(error.NotBlockAligned, Des.decrypt(&privacy_key, s, ciphertext[0..7], &back)); try testing.expectError(error.NotBlockAligned, Des.decrypt(&privacy_key, s, "", &back)); } test "AES privacy round-trips and needs no padding" { const privacy_key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c, }; const s = Aes.salt(0x0102030405060708); try testing.expectEqualSlices(u8, &.{ 1, 2, 3, 4, 5, 6, 7, 8 }, &s.bytes); // Every length, because CFB's final partial block is where such a mode // goes wrong and a scoped PDU is whatever length it happens to be. for ([_]usize{ 1, 15, 16, 17, 31, 33, 100 }) |len| { const plaintext = @as([100]u8, @splat(0xa5))[0..len]; var buffer: [100]u8 = undefined; const ciphertext = Aes.encrypt(&privacy_key, 1, 12345, s, plaintext, &buffer); // No padding at all, unlike DES. try testing.expectEqual(len, ciphertext.len); var back: [100]u8 = undefined; const decrypted = Aes.decrypt(&privacy_key, 1, 12345, s, ciphertext, &back); try testing.expectEqualSlices(u8, plaintext, decrypted); } // The IV is boots || time || salt, so a receiver whose notion of time has // moved builds a different IV and gets rubbish. That is a real failure // mode of v3 rather than a hypothetical one. const plaintext = "scoped PDU"; var buffer: [32]u8 = undefined; const ciphertext = Aes.encrypt(&privacy_key, 1, 12345, s, plaintext, &buffer); var back: [32]u8 = undefined; const wrong = Aes.decrypt(&privacy_key, 1, 12346, s, ciphertext, &back); try testing.expect(!std.mem.eql(u8, plaintext, wrong)); } test "a key longer than the hash produces is extended, not repeated" { // AES-256 wants 32 octets and SHA-1's derivation gives 20, so the key is // chained rather than truncated -- and the second chunk must not simply // be the first again, which is the mistake a careless extension makes. const engine_id = [_]u8{ 0x80, 0x00, 0x1f, 0x88, 0x01, 0x02, 0x03 }; var key: [32]u8 = undefined; extendKey(.hmac_sha1_96, "maplesyrup", &engine_id, &key); // The first 20 octets are exactly the ordinary localized key, so an // extension cannot change what a shorter protocol would have got. var plain: [20]u8 = undefined; privacyKey(.hmac_sha1_96, .aes_128_cfb, "maplesyrup", &engine_id, plain[0..16]); try testing.expectEqualSlices(u8, plain[0..16], key[0..16]); // And the rest is new material rather than a repeat. try testing.expect(!std.mem.eql(u8, key[0..12], key[20..32])); // Extension is engine-specific all the way down: the chain feeds the // *localized* key back in, so a different engine changes every octet // rather than only the first chunk. var other: [32]u8 = undefined; const other_engine = [_]u8{ 0x80, 0x00, 0x1f, 0x88, 0x01, 0x02, 0x04 }; extendKey(.hmac_sha1_96, "maplesyrup", &other_engine, &other); try testing.expect(!std.mem.eql(u8, key[20..32], other[20..32])); // A protocol whose hash already produces enough is not extended at all. var short: [32]u8 = undefined; privacyKey(.hmac_sha256_192, .aes_256_cfb, "maplesyrup", &engine_id, &short); var sha256_kul: [32]u8 = undefined; var ku: [32]u8 = undefined; passwordToKey(.hmac_sha256_192, "maplesyrup", &ku); localizeKey(.hmac_sha256_192, &ku, &engine_id, &sha256_kul); try testing.expectEqualSlices(u8, &sha256_kul, &short); } test "the privacy key is the authentication derivation truncated to 16" { // With SHA-512 the authentication key is 64 octets and the privacy key is // the first 16 of the same derivation, so a stronger hash buys no extra // privacy key material. RFC 3826 §3.1.2.1 says so and RFC 7860 keeps it. const user: User = .{ .name = "someone", .level = .auth_priv, .auth = .hmac_sha512_384, .priv = .aes_128_cfb, .auth_password = "maplesyrup", .priv_password = "maplesyrup", }; var keys = Keys.derive(user, &rfc3414_engine_id); try testing.expectEqual(@as(usize, 64), keys.authKey().len); try testing.expectEqual(@as(usize, 16), keys.privKey().len); // Same password for both, so the privacy key is a prefix of the // authentication key. try testing.expectEqualSlices(u8, keys.authKey()[0..16], keys.privKey()); } test "localization is what makes one password fifty keys" { const user: User = .{ .name = "someone", .level = .auth_no_priv, .auth = .hmac_md5_96, .auth_password = "maplesyrup", }; var a = Keys.derive(user, &.{ 0x80, 0x00, 0x1f, 0x88, 0x01 }); var b = Keys.derive(user, &.{ 0x80, 0x00, 0x1f, 0x88, 0x02 }); // One octet of engine ID apart, and nothing in common. This is the whole // point: a key recovered from one device does not open the next. try testing.expect(!std.mem.eql(u8, a.authKey(), b.authKey())); try testing.expectEqual(a.authKey().len, b.authKey().len); } test "a level that asks for more than the protocols provide" { try testing.expect((User{ .name = "someone" }).isConsistent()); // A name is not optional. try testing.expect(!(User{ .name = "" }).isConsistent()); // authNoPriv with no protocol, or no password, is a configuration mistake // that would otherwise appear as an unexplained rejection from the agent. try testing.expect(!(User{ .name = "x", .level = .auth_no_priv }).isConsistent()); try testing.expect(!(User{ .name = "x", .level = .auth_no_priv, .auth = .hmac_md5_96, }).isConsistent()); try testing.expect((User{ .name = "x", .level = .auth_no_priv, .auth = .hmac_md5_96, .auth_password = "p", }).isConsistent()); // authPriv needs both halves. try testing.expect(!(User{ .name = "x", .level = .auth_priv, .auth = .hmac_md5_96, .auth_password = "p", }).isConsistent()); try testing.expect((User{ .name = "x", .level = .auth_priv, .auth = .hmac_md5_96, .auth_password = "p", .priv = .des_cbc, .priv_password = "q", }).isConsistent()); } test "the names net-snmp uses on the command line" { try testing.expectEqual(AuthProtocol.hmac_md5_96, AuthProtocol.parse("MD5").?); try testing.expectEqual(AuthProtocol.hmac_sha1_96, AuthProtocol.parse("SHA").?); try testing.expectEqual(AuthProtocol.hmac_sha256_192, AuthProtocol.parse("SHA-256").?); try testing.expectEqual(AuthProtocol.hmac_sha512_384, AuthProtocol.parse("sha-512").?); try testing.expectEqual(@as(?AuthProtocol, null), AuthProtocol.parse("SHA-3")); try testing.expectEqual(@as(?AuthProtocol, null), AuthProtocol.parse("")); try testing.expectEqual(PrivProtocol.des_cbc, PrivProtocol.parse("DES").?); try testing.expectEqual(PrivProtocol.aes_128_cfb, PrivProtocol.parse("AES").?); try testing.expectEqual(PrivProtocol.aes_256_cfb, PrivProtocol.parse("AES-256").?); try testing.expectEqual(PrivProtocol.aes_256_cfb, PrivProtocol.parse("aes256").?); try testing.expectEqual(PrivProtocol.aes_192_cfb, PrivProtocol.parse("AES-192").?); try testing.expectEqual(PrivProtocol.aes_192_cfb, PrivProtocol.parse("aes192").?); try testing.expectEqual(PrivProtocol.des3_cbc, PrivProtocol.parse("3DES").?); try testing.expectEqual(PrivProtocol.des3_cbc, PrivProtocol.parse("3desede").?); // Everything USM ever defined is here. What is refused is a name for // something that does not exist rather than one this cannot do. try testing.expectEqual(@as(?PrivProtocol, null), PrivProtocol.parse("AES-GCM")); try testing.expectEqual(@as(?PrivProtocol, null), PrivProtocol.parse("ChaCha20")); try testing.expectEqual(SecurityLevel.no_auth_no_priv, SecurityLevel.parse("noAuthNoPriv").?); try testing.expectEqual(SecurityLevel.auth_no_priv, SecurityLevel.parse("authNoPriv").?); try testing.expectEqual(SecurityLevel.auth_priv, SecurityLevel.parse("authPriv").?); try testing.expectEqual(@as(?SecurityLevel, null), SecurityLevel.parse("authPrив")); // And the flag bits, which are what actually goes on the wire. try testing.expectEqual(@as(u8, 0x00), SecurityLevel.no_auth_no_priv.flags()); try testing.expectEqual(@as(u8, 0x01), SecurityLevel.auth_no_priv.flags()); try testing.expectEqual(@as(u8, 0x03), SecurityLevel.auth_priv.flags()); } test "3DES takes 24 octets of key and eight of pre-IV" { // Draft-reeder splits its 32-octet localized key exactly as single DES // splits its 16: key first, pre-IV last. Getting the boundary wrong gives // a cipher keyed on the pre-IV and an IV built from key material, which // fails in a way that looks like a wrong password. try testing.expectEqual(@as(usize, 32), PrivProtocol.des3_cbc.keyLength()); try testing.expectEqual(@as(usize, 24), Des3.key_octets); const privacy_key = [_]u8{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, }; const s = Des3.salt(3, 99); // The same salt construction as single DES, which is the point of the // design: an implementation that had DES only had to widen the key. try testing.expectEqualSlices(u8, &Des.salt(3, 99).bytes, &s.bytes); const plaintext = "a scoped PDU of some length or other"; var buffer: [64]u8 = undefined; const ciphertext = Des3.encrypt(&privacy_key, s, plaintext, &buffer); try testing.expectEqual(Des.paddedLength(plaintext.len), ciphertext.len); var back: [64]u8 = undefined; const decrypted = try Des3.decrypt(&privacy_key, s, ciphertext, &back); try testing.expectEqualStrings(plaintext, decrypted[0..plaintext.len]); // Changing a pre-IV octet changes the ciphertext, which says those eight // are reaching the IV and not the key schedule. var other = privacy_key; other[24] ^= 0xff; var buffer2: [64]u8 = undefined; try testing.expect(!std.mem.eql(u8, ciphertext, Des3.encrypt(&other, s, plaintext, &buffer2))); // And changing a *key* octet changes it too, differently: the first block // differs as well, which it would not if only the IV had moved. var third = privacy_key; third[0] ^= 0xff; var buffer3: [64]u8 = undefined; const keyed = Des3.encrypt(&third, s, plaintext, &buffer3); try testing.expect(!std.mem.eql(u8, ciphertext[0..8], keyed[0..8])); // Not whole blocks was not made by this mode. try testing.expectError( error.NotBlockAligned, Des3.decrypt(&privacy_key, s, ciphertext[0 .. ciphertext.len - 1], &back), ); } test "3DES with three equal keys is single DES, which the key layout must not assume" { // `zig-std-crypto-ext` guarantees that 3DES with K1=K2=K3 equals single // DES. That means a 32-octet key whose first 24 octets repeat would give // the *same* ciphertext as single DES on the first 8 -- a useful sanity // check that the EDE ordering is right rather than, say, EEE. var privacy_key: [32]u8 = undefined; const k = [_]u8{ 0x13, 0x34, 0x57, 0x79, 0x9b, 0xbc, 0xdf, 0xf1 }; @memcpy(privacy_key[0..8], &k); @memcpy(privacy_key[8..16], &k); @memcpy(privacy_key[16..24], &k); // A pre-IV of zeroes, and a zero salt, so the IV is zero and CBC's first // block is the plaintext block unchanged. @memset(privacy_key[24..32], 0); const s: Salt = .{ .bytes = @splat(0) }; const plaintext = "abcdefgh"; var triple: [16]u8 = undefined; const from_3des = Des3.encrypt(&privacy_key, s, plaintext, &triple); var single_key: [16]u8 = undefined; @memcpy(single_key[0..8], &k); @memset(single_key[8..16], 0); var single: [16]u8 = undefined; const from_des = Des.encrypt(&single_key, s, plaintext, &single); try testing.expectEqualSlices(u8, from_des, from_3des); }