diff --git a/bitchat/Protocols/BinaryEncodingUtils.swift b/bitchat/Protocols/BinaryEncodingUtils.swift index 10c14c993..1dcfe7c1f 100644 --- a/bitchat/Protocols/BinaryEncodingUtils.swift +++ b/bitchat/Protocols/BinaryEncodingUtils.swift @@ -23,20 +23,42 @@ extension Data { return digest.map { String(format: "%02x", $0) }.joined() } + /// Initialize Data from a hex string. + /// - Parameter hexString: A hex string, optionally prefixed with "0x" or "0X". + /// Whitespace is trimmed. Must have even length after prefix removal. + /// - Returns: nil if the string has odd length or contains invalid hex characters. init?(hexString: String) { - let len = hexString.count / 2 + var hex = hexString.trimmingCharacters(in: .whitespaces) + + // Remove optional 0x prefix + if hex.hasPrefix("0x") || hex.hasPrefix("0X") { + hex = String(hex.dropFirst(2)) + } + + // Reject odd-length strings + guard hex.count % 2 == 0 else { + return nil + } + + // Reject empty strings + guard !hex.isEmpty else { + self = Data() + return + } + + let len = hex.count / 2 var data = Data(capacity: len) - var index = hexString.startIndex - + var index = hex.startIndex + for _ in 0..