Converting SQL Server CAST Hexadecimal Strings to Text in .NET

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?

Your byte array handling and hex string processing are the problem. SQL Server stores NVARCHAR as UTF-16LE - each character needs two bytes. Your manual parsing is on the right track but needs tweaking. Strip the ‘0x’ prefix first and make sure what’s left has an even number of characters. Convert each hex pair to bytes, then use Encoding.Unicode.GetString() on the byte array. I ran into this same thing analyzing obfuscated SQL injections. You’ve got to validate your hex string format before parsing - bad strings will throw exceptions. Wrap your byte parsing in try-catch blocks and double-check that your byte count matches what you expect. This method’s been solid for me when decoding SQL Server hex payloads in forensic work.

Nice security analysis work! Are you handling the 0x prefix correctly when parsing? Also, does your hex string always have an even number of characters after removing the prefix? Padding issues can cause weird failures on specific values.

your hex parsing is almost right, but handle the 0x prefix first. strip it off, then use Convert.FromHexString() if ur on .NET 5+. otherwise, fix ur loop bounds - looks like you’re getting index errors at the end.