The attached code is a function that plugs XSS vulnerabilities in a CGI app I'm working on. See http://en.wikipedia.org/wiki/XSS for a good definition of XSS.

This function escapes characters that are not found in the constant XXSS_ALLOWED_CHARS.

I'd like to optimize this in several ways, ordered by importance:
This function needs to filter all characters that can be used for XSS vulnerabilities (i.e. I need to prevent someone from putting html and/or javascript into a search query and having it executed.) I want to do this by escapeing the character rather than removing the character.

Optimize for speed/memory usage, etc.

I'd like to not use the Microsoft.VisualBasic namespace if possible.

Thanks for any help or other pointers I get.
VB Code:
  1. Public Function XXSSFilter(ByVal UnfilteredText As String) As String
  2.         Const XXSS_ALLOWED_CHARS As String = " !$%*+,-./0123456789:=?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_abcdefghijklmnopqrstuvwxyz|~"
  3.         'Filters strings to be sent to the client. Used to prevent XSS vulnerabilities
  4.         'Only certain characters need to be escaped.
  5.  
  6.         Dim i As Integer
  7.         Dim sBuffer As String = ""
  8.  
  9.         With UnfilteredText
  10.             'split the string into charachters. check if each character is in XCODE_ALLOWED_CHARS.
  11.             'if not, replace [character] with '&#[character #];'
  12.             For i = 0 To .Length - 1
  13.                 If InStr(XXSS_ALLOWED_CHARS, .Chars(i), CompareMethod.Binary) = 0 Then
  14.                     'escape the character
  15.                     sBuffer += "&#" & Asc(.Chars(i)) & ";"
  16.                 Else
  17.                     'pass the character
  18.                     sBuffer += .Chars(i)
  19.                 End If
  20.             Next
  21.  
  22.             Return sBuffer
  23.         End With
  24.     End Function