I’m working on a security analysis tool and need help converting encoded SQL commands back to readable text. The malicious code I’m dealing with uses hexadecimal encoding and looks like this:
DECLARE @var NVARCHAR(4000);SET @var=CAST(0x5400650073007400 AS NVARCHAR(4000));EXEC(@var);
I need to decode the hex portion without running it through SQL Server for safety reasons. The key part is:
CAST(0x5400650073007400 AS NVARCHAR(4000))
I’ve attempted several approaches but none work correctly:
resultText.Text = HttpUtility.UrlDecode(inputText.Text);
resultText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(inputText.Text));
resultText.Text = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(inputText.Text));
I also tried parsing hex pairs manually:
while (!isComplete)
{
currentByte = byte.Parse(sourceText.Text.Substring(currentIndex, 2), NumberStyles.HexNumber);
byteArray[arrayIndex] = currentByte;
currentIndex += 2;
arrayIndex++;
if (sourceText.Text.Length - currentIndex < 2)
{
isComplete = true;
}
}
resultText.Text = Encoding.Unicode.GetString(byteArray);
The parsing fails on certain hex values. What’s the correct approach to handle this SQL Server hex encoding in C# or VB.NET?