Programming and Scripting :: Convert ascii wifi key to hex



Yes. I can also think for situations where you would want to check if it's still correct, without going to the browser, the router config page, logging in etc and then using this in asci2hex way..
Some programs give the key with the dash after every four characters, some with colon after every two. It doesn't really matter, as they are just there to ease reading, and if you happen to give the "wrong" one, the program will just convert it to the form it likes better.
That clarifies that.
Curaga, here's quick 'n' dirty reverse:

Code Sample

#!/bin/bash

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

echo $1 | sed 's/[-:]//g' | while read -n 2 HEXCH; do printf "%s\x$HEXCH" 2>/dev/null; done | sed 's/\\\x$/\n/'


Will ignore - or : in input.

These are for 13 char asci-equivalent keys.

A Perl version, since I definitely need the practice:

Code Sample
#!/usr/bin/perl


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

use strict;
use warnings;

my $hexkey = shift;
chomp $hexkey;
$hexkey =~ s/^[+]+//;  # or can't cope with a leading +
$hexkey =~ s/[:-]//g;

# Insert space every 2 chars
$hexkey =~ s/([^\s]{2})/$1 /gs;

my @A = split (/ /, $hexkey);

foreach my $c (@A){
my $dec = hex($c);
print chr($dec);
}

print "\n";



EDIT:   Perl version as is can't cope with $ as an illegal input hex char.   Gives superior built-in error messaging and tells you that it is ignoring which illegal hex chars.

The bash script runs in around the same time or faster, despite the pipes (subshells), read and 2 sed invocations - not that speed matters here.

Equivalent functionality in bash to both flag and remove illegal hex chars is like:

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' | while read -n 2 HEXCH; do
printf "%s\x$HEXCH" 2>/dev/null; done | sed 's/\\\x$//'

echo


which is more sed than I usually care to learn and shows why I like Perl.  No doubt this could be made better. To cope with $ as a non-hex input char, bash script argument needs to be put in single quotes.

A more readable alternative bash script might parse the input char by char instead.

Next Page...
original here.