Nmap Development mailing list archives

[NSE][PATCH] string.to_hex() function


From: Sven Klemm <sven () c3d2 de>
Date: Wed, 10 Sep 2008 16:25:16 +0200

Hi everyone,

I've written a to_hex() function for the lua string class.
string.to_hex(string, separator = "", group_length = 1)
separator and group_length are optional. Separator will be added to the string after each byte or after group_length bytes when group_length is passed.

Here are a few examples:

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

I think this function is extremely useful for any script that wants to display hexencoded data as this function would be available on every string. But I am not sure myself whether it is the best way to add this functionality. Do you think this function should be added to string or are there better ways to implement this. The main reason for this patch is so we don't have to implement a hash_raw() and a hash_hex() function for every hashing algorithm but the function is surely useful in a lot of other places too.


Cheers,
Sven

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

Index: nse_init.cc
===================================================================
--- nse_init.cc (revision 10060)
+++ nse_init.cc (working copy)
@@ -24,6 +24,8 @@
 #include "errno.h"
 
 #include <algorithm>
+#include <sstream>
+#include <iomanip>
 
 extern NmapOps o;
 
@@ -217,6 +219,31 @@
   return 0;
 }
 
+/* int string_to_hex(lua_State *L)
+ *
+ * string.to_hex( string, separator, group_length )
+ */
+int string_to_hex(lua_State *L)
+{
+  size_t len,i;
+  const unsigned char * s = (unsigned char *) luaL_checklstring( L, 1, &len );
+  const char * separator = luaL_optstring( L, 2, NULL );
+  size_t group_length = luaL_optint( L, 3, 1 );
+  if ( group_length < 1 ) group_length = 1;
+
+  std::ostringstream ret;
+  ret << std::setbase(16) << std::setfill('0');
+
+  for(i=0;i<len;i++) {
+    if ( separator && i && i % group_length == 0 ) 
+      ret << separator;
+    ret << std::setw(2) << (unsigned int) s[i];
+  }
+  
+  lua_pushstring( L, ret.str().c_str() );
+  return 1;
+}
+
 /* int init_lua (lua_State *L)
  *
  * Initializes the Lua State.
@@ -267,6 +294,13 @@
   lua_pushcclosure(L, error_function, 1);
   errfunc = luaL_ref(L, LUA_REGISTRYINDEX);
 
+  // add to_hex function to string
+  lua_getglobal(L, "string");
+  lua_pushstring(L, "to_hex");
+  lua_pushcfunction(L, string_to_hex);
+  lua_settable(L,-3);
+  lua_pop(L, 1);
+
   lua_pushcclosure(L, init_setpath, 0);
   lua_call(L, 0, 0);
   

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

Current thread: