Programming and Scripting :: Convert ascii wifi key to hex



Continuing explorations, may be of limited interest to anyone else but at least I'll know where to find it again.

Doing away with while and read:

Code Sample
#!/bin/bash

#
# hex2ascikey.sh
# Takes hex wifi key as argument and prints asci
#
echo -n $1 | sed  's/[0-9A-Fa-f]//g
t message
:message s/.\*/Ignoring non-hex chars &\n/'

echo -n $1 | sed 's/[^0-9A-Fa-f]//g; s/../\"%s\\x&\"/g' | xargs printf

echo


I'm not really sure why that t branching test works quite as it does.    So thought I'd try to do without it and let sed take over:

Code Sample

#!/bin/bash

#
# hex2ascikey.sh
# Takes hex wifi key as argument and prints asci
#

echo -n $1 | sed '
H
s/[0-9A-Fa-f]//g
/[^0-9A-Fa-f]/{
s/^/\"Ignoring non-hex chars \"/
}
x
s/[^0-9A-Fa-f]//g
s/../\"%s\\x&\"/g
s/^/"%s\n"/
G
' | xargs printf

echo

Or Sed-free, parse char-by-char:
Code Sample

#
# hex2ascikey.sh
# Takes hex wifi key as argument and prints asci
#

ASC=""
IGNORED=""
igntemp=`mktemp`

echo -n $1 | while read -n 1 CH; do

case $CH in
[0-9A-Fa-f])
ASC="${ASC}${CH}"
if [ ${#ASC} -eq 2 ]; then
printf "%s\x$ASC"
ASC=""
fi;;
*) IGNORED="${IGNORED}${CH}"
;;
esac
echo ${IGNORED} >${igntemp}
done
echo
echo "Ignored non-hex chars `cat ${igntemp}`"
rm -f ${igntemp}


Slower, even without the temp file.

Bettter: no subshell, no read, no temp file.

Still less efficient than sed, but then sed is made to do this stuff.

Code Sample
#!/bin/bash

#
# hex2ascikey.sh
# Takes hex wifi key as argument and prints asci
#


ASC=""
IGNORED=""


A="$1"


until [ ${#A} -eq 0 ]; do
B=${A#?}
CH=${A%%$B}

case $CH in
[0-9A-Fa-f])
ASC="${ASC}${CH}"
if [ ${#ASC} -eq 2 ]; then
printf "%s\x$ASC"
ASC=""
fi;;
*) IGNORED="${IGNORED}${CH}"
;;
esac
A=${B}
done

echo
[ -n  "${IGNORED}" ] && echo "Ignored non-hex chars ${IGNORED}"

Yes, I know, (groan), "he still hasn't given up on this thread".

(Pls bear with me while I post my self-education exercises).

Much easier in C:

Code Sample
//~ asci2hex - converts ascii wifi key to hex

#include <stdio.h>

main()
{
char ch;
printf("Enter the ascii key: ");
while ( ch= ' ' ){
ch = getchar();
if (ch == '\n')
break;
printf("%X", ch);
}
printf("\n");
}


And (todo: doesn't yet report any ignored non-hex input):

Code Sample
//~ asci2hex - converts hex wifi key to ascii

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


char hexToAscii(char first, char second)
//~ http://snippets.dzone.com/posts/show/2073
{
char hex[3], *stop;
hex[0] = first;
hex[1] = second;
hex[2] = 0;
return strtol(hex, &stop, 16);
}


main()
{
char ch1, ch2;

printf("Enter the hex key: ");
while (1){
ch1 = getchar();
if (ch1 == '\n')
break;
if (!isxdigit(ch1))
continue;
ch2 = getchar();
if (ch2 == '\n')
break;
if (!isxdigit(ch2))
continue;
printf("%c", hexToAscii(ch1, ch2));
}
printf("\n");
}


original here.