Hiding my password

Following Alastair’s post regarding encrypting sections of a configuration file I ran into a similar issue where I wanted to protect a password that my application was using.  Obviously there are a couple of big NO NOs. I can’t hard code the password into the application because it is too easy to use something like Reflector to crack it own and grab the password in clear text.  I can’t easily use the standard crypto functions that require a private key, cause then I would have to hide the private key somewhere).  Luckily v2 of the .NET Framework exposes DPAPI through the ProtectedData class.  As such I can do the following to encrypt/decrypt data:

    Private pData As Byte()
    Private Sub Encrypt()

        Dim sensitiveData As Byte() = System.Text.Encoding.Unicode.GetBytes(“Some sensitive data”)
        pdata = ProtectedData.Protect(sensitiveData, Nothing, DataProtectionScope.CurrentUser)
    End Sub

    Private Sub Decrypt()
        Dim sensitiveData As Byte() = ProtectedData.Unprotect(pData, Nothing, DataProtectionScope.CurrentUser)
        Dim str As String = System.Text.Encoding.Unicode.GetString(sensitiveData)
    End Sub

You will of course need to add a reference to System.Security to your application and import the System.Security.Cryptography namespace into your code file.

Leave a comment