// Everything derived from the security key string itself: the magic number // that frames every packet, and the key's validity, generation and display // rules. See docs/protocol.md §2.1 and §2.4. // // Ported from App/Core/Encryption.cs. import CryptoKit import Foundation /// The 32-bit magic number derived from the security key. /// /// Only its top 16 bits go on the wire (`Framing`), but the whole value is /// what a peer compares against, so it must be reproduced bit for bit. public enum MagicHash { /// Number of times the SHA-512 digest is re-hashed after the first pass /// (`Encryption.cs:192`); 50 001 digests in total. private static let rehashRounds = 50_000 /// `Get24BitHash(key)` (`Encryption.cs:173-200`). /// /// The key is written into a fixed 32-byte zero buffer, one byte per /// UTF-16 code unit **truncated to eight bits** (`Encryption.cs:185`), so /// a non-ASCII key hashes to whatever the low bytes of its code units are — /// matching Windows rather than being correct. public static func magicNumber(for key: String) -> UInt32 { guard !key.isEmpty else { return 0 } // Encryption.cs:175-178 var buffer = [UInt8](repeating: 0, count: packageSize) // Encryption.cs:180 for (i, unit) in key.utf16.enumerated() { guard i < packageSize else { break } // Encryption.cs:181-183 buffer[i] = UInt8(truncatingIfNeeded: unit) } var digest = [UInt8](SHA512.hash(data: buffer)) for _ in 0...?/\\|[]", ] /// Whether a key may be used; validation is length-only, as on Windows /// (`Encryption.cs:235-242`). There is no weak-key or charset check there /// and adding one here would reject keys a Windows peer accepts. public static func isValid(_ key: String) -> Bool { key.count >= minimumLength } /// A key as typed by the user, with all whitespace discarded /// (`Form/Settings/SetupPage2a.cs:92`) — the same normalisation that makes /// the grouped `displayText` form safe to copy between machines. public static func normalize(_ typed: String) -> String { typed.filter { !$0.isWhitespace } } /// A fresh 16-character key, one character taken round-robin from each of /// the four sets (`Encryption.cs:209-233`). /// /// Windows takes a random byte and reduces it modulo the set size, which is /// slightly biased; `randomElement()` over `SystemRandomNumberGenerator` is /// not, and nothing on the wire depends on how the key was chosen. public static func random() -> String { var key = "" while key.count < minimumLength { for set in charsets { guard let c = set.randomElement() else { continue } key.append(c) if key.count >= minimumLength { break } // Encryption.cs:224-227 } } return key } /// The key in groups of four separated by two spaces, as the Windows UI /// shows it (`KeyDisplayedText`, `Encryption.cs:65-79`). `normalize` /// reverses it. public static func displayText(_ key: String) -> String { let chars = Array(key) var out = "" var i = 0 repeat { let end = min(i + 4, chars.count) out += String(chars[i..