Solved

Converting a JavaScript Snippet to a command line tool

Posted on 2008-06-24
9
301 Views
Last Modified: 2012-08-14
I Basically got this Code from a website which converts Hex to Ascii and it gives me whatever i need
is there anyway i can convert this code to an execuatble which returns the output to a txt file?

i only need the Hex - > Ascii Part

taken from
http://www.dolcevie.com/js/converter.html

Thanks

A Complete Code Dummy
<!-- saved from url=(0022)http://internet.e-mail -->

<html>

<head>

<title>Hex/Ascii Converter</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 

<script>
 

var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";

var loAZ = "abcdefghijklmnopqrstuvwxyz";

symbols+= loAZ.toUpperCase();

symbols+= "[\\]^_`";

symbols+= loAZ;

symbols+= "{|}~";
 

function toAscii()

{

	valueStr = document.form1.hex.value;

	valueStr = valueStr.toLowerCase();

    var hex = "0123456789abcdef";

	var text = "";

	var i=0;

	

	for( i=0; i<valueStr.length; i=i+2 )

	{

		var char1 = valueStr.charAt(i);

		if ( char1 == ':' ) 

		{

			i++;

			char1 = valueStr.charAt(i);

		}		

		var char2 = valueStr.charAt(i+1);

		var num1 = hex.indexOf(char1);

		var num2 = hex.indexOf(char2);

		var value = num1 << 4;

		value = value | num2;

				

		var valueInt = parseInt(value);

		var symbolIndex = valueInt - 32;		

		var ch = '?';

		if ( symbolIndex >= 0 && value <= 126 )

		{		

			ch = symbols.charAt(symbolIndex)

		}

		text += ch;				

	}

	

	document.form1.ascii.value = text;

	return false;

}
 

function toHex()

{

	var valueStr = document.form1.ascii.value;

	var hexChars = "0123456789abcdef";

	var text = "";

	for( i=0; i<valueStr.length; i++ )

	{

		var oneChar = valueStr.charAt(i);

		var asciiValue = symbols.indexOf(oneChar) + 32;

		var index1 = asciiValue % 16;

		var index2 = (asciiValue - index1)/16;

		if ( text != "" ) text += ":";

		text += hexChars.charAt(index2);

		text += hexChars.charAt(index1);			

	}

	document.form1.hex.value = text;

	return false;

}
 
 

</script>
 
 

</head>
 

<body>
 
 
 

<p><font face="Geneva, Arial, Helvetica, sans-serif"><strong>Hex To ASCII Converter</strong></font></p>

<form name="form1" method="post" action="">

  <table width="78%" border="0" cellpadding="5" cellspacing="5">

    <tr> 

      <td width="13%"><font size="-1" face="Geneva, Arial, Helvetica, sans-serif">Hex: 

        </font></td>

      <td width="76%"><textarea name="hex" cols="80" rows="3" id="hex">41:6e:74:6f:6e:20:69:73:20:67:72:65:61:74:20:3a:29</textarea></td>

    </tr>

    <tr> 

      <td><font size="-1" face="Geneva, Arial, Helvetica, sans-serif">Ascii:</font></td>
 

      <td><textarea name="ascii" cols="80" rows="3" id="ascii"></textarea></td>

    </tr>

  </table>

  <p> 

    <input name="b1" type="submit" id="b13" value="Hex To ASCII" onClick="return toAscii();">

    <input name="b2" type="submit" id="b14" value="ASCII To Hex" onClick="return toHex();">

  </p>

  <p>&nbsp;</p>

</form>
 

<p>&nbsp;</p>

<p>&nbsp;</p>

</body>

</html>

Open in new window

0
Comment
Question by:m0tek
  • 6
  • 2
9 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 21855967
Do you have a particular language in which you prefer it to be written?

For example, if you don't have a compiler, you really don't want it written
in a language that needs to be compiled.  However, this is a mute point
if you can get a "free" compiler (e.g., GNU C, or Java).

Another possibility would be for it to be written in a different scripting
language for which the interpreter is freely available (e.g., Python, or Perl).

What do you want?
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 21856639
Python script:

if you don't know, you can get Python from

ActiveState.com/python
#--------------------------------------------------------------------

# Name: HexToAscii

# Role: Convert Hext to Ascii, or Ascii to Hex

#--------------------------------------------------------------------

import re, sys;
 

#--------------------------------------------------------------------

# Name: Usage()

# Role:

#--------------------------------------------------------------------

def Usage( cmd = 'HexToAscii' ):

  pos = cmd.rindex( '\\' )

  if pos > -1 :

    cmd = cmd.split( '\\' )[ -1 ]

  if cmd.endswith( '.py' ) :

    cmd = cmd[ :-3 ]

  print '''

%s.py - Convert from Hex to Ascii, or Ascii to Hex\n

python %s.py [-a|-h] text\n

Where: -a : requests conversion from Hex to Ascii

       -h : requests conversion from Ascii to Hex\n

Example: python %s.py -h Testing

         python %s.py -a 54:65:73:74

  ''' % ( ( cmd, ) * 4 )

  sys.exit()
 

#--------------------------------------------------------------------

# Name: toAscii()

# Role:

#--------------------------------------------------------------------

def toAscii( text ) :

  if re.match( '[0-9a-fA-F]{2}(?::[0-9a-fA-F]{2})*$',text ) :

    msg = ''

    for x in text.split( ':' ) :

      msg += chr( eval( '0x' + str( x ) ) )

    print msg

  else :

    print 'Invalid hex pattern: ' + text
 

#--------------------------------------------------------------------

# Name: toHex()

# Role:

#--------------------------------------------------------------------

def toHex( text ) :

  msg = ''

  for ch in text :

    msg += ':' + str( hex( ord( ch ) ) )[ 2: ];

  print msg[ 1: ]
 

#--------------------------------------------------------------------

# Main program entry point - test to see how the script was executed

#--------------------------------------------------------------------

if __name__ == '__main__' :

  argc = len( sys.argv )

  if argc > 2 :

    cmd = sys.argv[ 1 ];

    if cmd == '-h' :

      toHex( ' '.join( sys.argv[ 2: ] ) );

    elif cmd == '-a' :

      toAscii( ' '.join( sys.argv[ 2: ] ) );

    else :

      Usage( sys.argv[ 0 ] );

  else :

    Usage( sys.argv[ 0 ] );

Open in new window

0
 

Author Comment

by:m0tek
ID: 21894297
Omg Honor , thanks for the code.

now i guess i need to download python and run it?
how exactly does it get the input and how does it output the output?

basically , im using this to decrypt SQL Injections which are hex coded
my SIEM system takes a string and tests that string (run command) to the command line tool

what i need is

Sql Injection Encoded - > ( i know how to extract the string ) - > raw string - > tool - > decrypted string (in a text file or on screen)

any ideas?
0
 
LVL 41

Expert Comment

by:HonorGod
ID: 21895147
Well, yes, you have to download the Python interpreter.
Once it is install, you need to make is so that Python programs can
be executed from the command line.

- What Operating System is being used?

The instructions for doing the previous depend on the OS.

For example, for Windows, you can use the ActiveState python executable
Then, you can tell the OS what Python programs are, and how to execute them.

For Linux, you have to do things a bit differently.  However, almost all Linux
installs have Python as part of the distribution.

How do you specify input values to Python Programs?

Easily.  1 way is to require that the parameters be specified on the command
line.  Then, you can  use some of the built-in packages/modules to retrieve the
user specified commands.

Another way is to have your program prompt for the user input.

From your description, it sounds like you just need a "filter", which is a "simple"
kind of program that process the data from "standard" input, and writes it to
"standard output".

Does this make sense?  Let me know
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:m0tek
ID: 21906096
Hi Honor ,

wierd thing - if i use the website javascript (in the website)
to convert 4445434C4152452 - > Declare

it goes well (u can try for yourself)

http://www.dolcevie.com/js/converter.html

But , if i use the script - here is the output i get

C:\>Script.py -a 4445434C415245
Invalid hex pattern: 4445434C415245

C:\>Script.py -a 4445434C4152452
Invalid hex pattern: 4445434C4152452

C:\>Script.py -a 44:45:43:4C:41:52:45:2
Invalid hex pattern: 44:45:43:4C:41:52:45:2

C:\>Script.py -a 44:45:43:4C:41:52:45
DECLARE


Is there a way to auto insert the ":" between every 2 chars?

0
 
LVL 1

Accepted Solution

by:
jmarnoch earned 250 total points
ID: 21986154
I converted your javascript file to work using windows script host, save it to a file (eg hex2ascii.js) somewhere, open command prompt

do this:

cscript hex2ascii.js 4445434C415245

or

cscript hex2ascii.js 4445434C415245 file.txt

first one will output to console, second one to file.txt

Hope this helps

James


var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";

var loAZ = "abcdefghijklmnopqrstuvwxyz";

symbols+= loAZ.toUpperCase();

symbols+= "[\\]^_`";

symbols+= loAZ;

symbols+= "{|}~";

 

function toAscii(input)

{

        valueStr = input;

        valueStr = valueStr.toLowerCase();

    var hex = "0123456789abcdef";

        var text = "";

        var i=0;

        

        for( i=0; i<valueStr.length; i=i+2 )

        {

                var char1 = valueStr.charAt(i);

                if ( char1 == ':' ) 

                {

                        i++;

                        char1 = valueStr.charAt(i);

                }               

                var char2 = valueStr.charAt(i+1);

                var num1 = hex.indexOf(char1);

                var num2 = hex.indexOf(char2);

                var value = num1 << 4;

                value = value | num2;

                                

                var valueInt = parseInt(value);

                var symbolIndex = valueInt - 32;                

                var ch = '?';

                if ( symbolIndex >= 0 && value <= 126 )

                {               

                        ch = symbols.charAt(symbolIndex)

                }

                text += ch;                             

        }

        

        return text;

}

 
 

var args = WScript.Arguments;
 

if(args.Count() == 0)

{

	WScript.Echo("Usage: cscript hex2ascii.js \"input text\" [<filename>]");

} 

else if(args.Count() == 1)

{

	WScript.Echo(toAscii(args.Item(0)));

}

else

{

	var fso = WScript.CreateObject("Scripting.FileSystemObject");

	var outputFile = fso.CreateTextFile(args.Item(1), true);

	outputFile.Write(toAscii(args.Item(0)));

	outputFile.Close();

}

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 21986336
Somehow I missed your update, and requested update.  One moment please...
0
 
LVL 41

Assisted Solution

by:HonorGod
HonorGod earned 250 total points
ID: 21986378
How's this?
#--------------------------------------------------------------------

# Name: HexToAscii

# Role: Convert Hext to Ascii, or Ascii to Hex

#--------------------------------------------------------------------

import re, sys;
 

#--------------------------------------------------------------------

# Name: Usage()

# Role:

#--------------------------------------------------------------------

def Usage( cmd = 'HexToAscii' ):

  pos = cmd.rindex( '\\' )

  if pos > -1 :

    cmd = cmd.split( '\\' )[ -1 ]

  if cmd.endswith( '.py' ) :

    cmd = cmd[ :-3 ]

  print '''

%s.py - Convert from Hex to Ascii, or Ascii to Hex\n

python %s.py [-a|-h] text\n

Where: -a : requests conversion from Hex to Ascii

       -h : requests conversion from Ascii to Hex\n

Example: python %s.py -h Testing

         python %s.py -a 54:65:73:74

  ''' % ( ( cmd, ) * 4 )

  sys.exit()
 

#--------------------------------------------------------------------

# Name: toAscii()

# Role:

#--------------------------------------------------------------------

def toAscii( text ) :

  if re.match( '[0-9a-fA-F]{2}(?::[0-9a-fA-F]{2})*$',text ) :

    msg = ''

    for x in text.split( ':' ) :

      msg += chr( eval( '0x' + str( x ) ) )

    print msg

  elif re.match( '[0-9a-fA-F]+', text ) and ( len( text ) % 2 == 0 ) :

    msg = ''

    while len( text ) > 0 :

      byte, text = text[ :2 ], text[ 2: ]

      msg += chr( eval( '0x' + str( byte ) ) )

    print msg

  else :

    print 'Invalid hex pattern: ' + text
 

#--------------------------------------------------------------------

# Name: toHex()

# Role:

#--------------------------------------------------------------------

def toHex( text ) :

  msg = ''

  for ch in text :

    msg += ':' + str( hex( ord( ch ) ) )[ 2: ];

  print msg[ 1: ]
 

#--------------------------------------------------------------------

# Main program entry point - test to see how the script was executed

#--------------------------------------------------------------------

if __name__ == '__main__' :

  argc = len( sys.argv )

  if argc > 2 :

    cmd = sys.argv[ 1 ];

    if cmd == '-h' :

      toHex( ' '.join( sys.argv[ 2: ] ) );

    elif cmd == '-a' :

      toAscii( ' '.join( sys.argv[ 2: ] ) );

    else :

      Usage( sys.argv[ 0 ] );

  else :

    Usage( sys.argv[ 0 ] );

Open in new window

0
 
LVL 41

Expert Comment

by:HonorGod
ID: 22655512
Thanks for the assist, and the points.

Good luck & have a blessed day
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Introduction:   Welcome to my first article ever. To begin with, the reason I write this article.  I participated in a question on Experts Exchange about the start command in Windows and there were some discussion about the usage. The discussio…
Batch, VBS, and scripts in general are incredibly useful for repetitive tasks.  Some tasks can take a while to complete and it can be annoying to check back only to discover that your script finished 5 minutes ago.  Some scripts may complete nearly …
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now