From d334620aa07f90aceec465e358da7e06bc498599 Mon Sep 17 00:00:00 2001 From: dmiller Date: Fri, 10 Mar 2017 17:29:51 +0000 Subject: [PATCH] New stdnse function 'fromhex' does hex decoding like bin.pack('H') --- nselib/stdnse.lua | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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