Problem Set 4 Supplemental Problem

Math 202 Cryptography, October 5, 2016
T. Ratliff, Wheaton College
ratliff_thomas@wheatoncollege.edu

Convert string to/from hex

stringTohexstring[str] will convert a 16-character string x to a 32-digit hexadecimal string representing the ASCII encoding of x
hexstringTostring[str] performs the opposite conversion

stringTohexstring[str_]:= Module[ {total,i,list},
If[StringLength[str]≠16, Return["** ERROR ** String must have length 16"]];
Return[IntegerString[Total[Flatten[Table[ToCharacterCode[StringTake[str,{i+1}]]*16^(2*(15-i)),{i,0,15}]]],16]
]];

hexstringTostring[h_]:=Module[{i},
Return[FromCharacterCode[Table[FromDigits[StringTake[h,{2i+1,2i+2}],16],{i,0,15}]]]
]

The stringTohexstring[ ] function will complain if your string is not the right length

stringTohexstring["This string is too long since it has more than 16 characters"]

stringTohexstring["Too short"]

stringTohexstring["Just right      "]

The hexstringTostring[ ] will convert a string of hex values to the corresponding ASCII characters

hexstringTostring["43727970746f67726170687921212121"]

hexstringTostring["4a757374207269676874202020202020"]

After you get the output from the AES emulator, here’s a handy function to remove all of the spaces from the string:

StringReplace["65 6c 6f 69"," " -> ""]