Click here to Skip to main content
15,886,258 members
Articles / Desktop Programming / Windows Forms

Securing Text Data in .NET

Rate me:
Please Sign up or sign in to vote.
4.15/5 (7 votes)
7 Dec 20066 min read 59.6K   661   36  
Discussion of securing text in an application. The example project contains a SecureString wrapper to make working with SecureString easier, and a textbox that directly manipulates a SecureString.
Imports System.Security
Imports System.ComponentModel

<DefaultEvent("SecureStringChanged")> _
Public Class SecureTextBox
    Inherits System.Windows.Forms.TextBox

#Region "Constructors"

    Public Sub New()
        MyBase.UseSystemPasswordChar = True
    End Sub

#End Region

#Region "Fields and Properties"

    Private WithEvents mSecureString As New SimpleSecureString
    ''' <summary>
    ''' Gets and sets the encrypted string associated with the SecureTextBox.
    ''' </summary>
    <Browsable(False)> _
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _
    Public Property SecureString() As SimpleSecureString
        Get
            Return mSecureString
        End Get
        Set(ByVal value As SimpleSecureString)
            mSecureString = value
            SetText()
            OnSecureStringChanged(EventArgs.Empty)
        End Set
    End Property

#End Region

#Region "Methods"

    ''' <summary>
    ''' Updates the TextBox with a string that represents
    ''' the secure string.
    ''' </summary>
    Private Sub SetText()
        MyBase.Text = New String("*"c, mSecureString.Length)
    End Sub

    ''' <summary>
    ''' Clears the secure string associated with the SecureTextBox.
    ''' </summary>
    Public Shadows Sub Clear()
        ' Unfortunately we can't override Clear.
        mSecureString.Clear()
    End Sub

#End Region

#Region "Event Handlers"

    Private Sub TextBox_KeyDown( _
            ByVal sender As Object, _
            ByVal e As KeyEventArgs) _
            Handles MyBase.KeyDown

        ' This method handles the Delete and Backspace keys.
        ' These keys are not sent to the KeyPress event.

        Dim ch As Char = Convert.ToChar(e.KeyValue)

        e.Handled = True
        e.SuppressKeyPress = True

        Dim caretPos As Integer = SelectionStart

        Select Case e.KeyCode
            Case Keys.Back
                If Me.SelectionLength > 0 Then
                    ' one or more characters are selected

                    mSecureString.Replace( _
                        "", _
                        SelectionStart, _
                        SelectionLength)

                ElseIf Me.SelectionStart > 0 Then
                    ' no characters are selected and we 
                    ' are not at the beginning of the text

                    mSecureString.RemoveAt( _
                        SelectionStart - 1)

                    caretPos -= 1
                Else
                    ' at the beginning of the text with 
                    ' nothing selected 
                    Return ' don't change the SelectionStart
                End If
            Case Keys.Delete
                If SelectionStart _
                    >= mSecureString.Length Then

                    ' at the end of the string
                    Return ' don't change the SelectionStart

                ElseIf SelectionLength > 0 Then
                    ' one or more characters are selected

                    mSecureString.Replace( _
                        "", _
                        SelectionStart, _
                        SelectionLength)

                Else
                    ' no characters are selected

                    mSecureString.RemoveAt( _
                        Me.SelectionStart)

                End If
            Case Else
                ' allow all other keys to be processed
                e.Handled = False
                e.SuppressKeyPress = False
                Return ' don't change the SelectionStart
        End Select

        ' we have to reset the SelectionStart because the 
        ' text is reset when the secure string changes
        Me.SelectionStart = caretPos
        Me.SelectionLength = 0
    End Sub

    Private Sub TextBox_KeyPress( _
            ByVal sender As Object, _
            ByVal e As KeyPressEventArgs) _
            Handles Me.KeyPress

        Dim ch As Char = e.KeyChar

        ' The KeyPress event is only raised for printable 
        ' chars. Control chars are handled in the KeyDown
        ' event handler.

        e.Handled = True

        Dim caretPos As Integer = SelectionStart

        If SelectionStart >= mSecureString.Length Then
            mSecureString.AppendChar(ch)
        ElseIf Me.SelectionLength > 0 Then

            mSecureString.Replace( _
                ch, _
                SelectionStart, _
                SelectionLength)

        Else
            mSecureString.InsertAt(caretPos, ch)
        End If

        ' we have to reset the SelectionStart because we 
        ' reset the text when the secure string changes
        SelectionStart = caretPos + 1
        SelectionLength = 0
    End Sub

    Private Sub mSecureString_SecureStringChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles mSecureString.SecureStringChanged
        SetText()
        OnSecureStringChanged(e)
    End Sub

#End Region

#Region "Events"

    Public Event SecureStringChanged(ByVal sender As Object, ByVal e As EventArgs)
    Protected Overridable Sub OnSecureStringChanged(ByVal e As EventArgs)
        RaiseEvent SecureStringChanged(Me, e)
    End Sub

#End Region

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I'm a software engineer in Spokane, WA. I have been developing with .Net since 2002. My main area of focus has been designing and implementing a UI framework for an ERP system. Before I got into .Net, I developed for several years in a variety of languages and platforms including mostly ASP, though I've also developed applications for both Palm and Pocket PC devices.

I received my degree in Computing and Software System from the University of Washington in 1999. I have also completed a certificate course in Object-Oriented Analysis and Design Using UML, also from the University of Washington, in 2005.

Comments and Discussions