Nmap Development mailing list archives

Re: [NSE][PATCH] string_ext library


From: Sven Klemm <sven () c3d2 de>
Date: Fri, 19 Sep 2008 22:05:33 +0200

Sven Klemm wrote:

i've attached a library that adds a to_hex function to string. I think this library would be a good place for adding further string enhancements like for example moving stdnse.strsplit() here.

example usage:

require "string_ext"

("abc"):to_hex() => "616263"
("abc"):to_hex(":") => "61:62:63"
("abc"):to_hex(":",2) => "6162:63"

I've attached a cleaned up version. I think this library is very useful as we don't have to implement two versions for certain functions anymore one providing binary strings the other providing hexadecimal encoded strings as it's currently done by the hash module. With this library any string can be effortlessly transformed into hexadecimal representation.

Cheers,
Sven

--
Sven Klemm
http://cthulhu.c3d2.de/~sven/

Index: nselib/string_ext.lua
===================================================================
--- nselib/string_ext.lua       (revision 0)
+++ nselib/string_ext.lua       (revision 10284)
@@ -0,0 +1,26 @@
+--- Extension for the lua string class
+
+module(... or "string_ext", package.seeall)
+
+setmetatable( string, {__index=string_ext})
+
+--- encode string to hexadecimal
+-- example: string.to_hex("abc") => "616263"
+--          string.to_hex("abc",{separator=":"}) => "61:62:63"
+--          string.to_hex("abc",{separator=":",group=2}) => "6162:63"
+--@param s string to be encoded
+--@param options table specifiying formatting options
+--@return hexadecimal encoded string
+to_hex = function( s, options ) 
+  options = options or {}
+  local group = options.group or 1
+  local separator = (options.separator or ""):gsub("%%","%%%%")
+
+  local fmt_table = {}
+  for i=1,#s,group do
+    table.insert( fmt_table, string.rep("%02x", math.min(#s-i+1,group)))
+  end
+
+  return table.concat( fmt_table, separator):format(s:byte(1, #s))
+end
+

_______________________________________________
Sent through the nmap-dev mailing list
http://cgi.insecure.org/mailman/listinfo/nmap-dev
Archived at http://SecLists.Org

Current thread: