diff --git a/nselib/stdnse.lua b/nselib/stdnse.lua index fde34a81b..68d97ec4d 100644 --- a/nselib/stdnse.lua +++ b/nselib/stdnse.lua @@ -403,6 +403,30 @@ function tohex( s, options ) return hex end +---Decode a hexadecimal string to raw bytes +-- +-- The string can contain any amount of whitespace and capital or lowercase +-- hexadecimal digits. There must be an even number of hex digits, since it +-- takes 2 hex digits to make a byte. +-- +-- @param hex A string in hexadecimal representation +-- @return A string of bytes or nil if string could not be decoded +-- @return Error message if string could not be decoded +function fromhex (hex) + local len = #hex + local out = {} + local i = 1 + while i <= len do + local p, q, c1, c2 = find(hex, "^%s*(%x)%s*(%x)%s*", i) + if not p then + return nil, format("Invalid characters or odd number of hex digits at %d", i) + end + out[#out+1] = char(tonumber(c1..c2, 16)) + i = q + 1 + end + return concat(out) +end + ---Format a MAC address as colon-separated hex bytes. --@param mac The MAC address in binary, such as host.mac_addr --@return The MAC address in XX:XX:XX:XX:XX:XX format