Hi,
I have to figure out why we have a problem with special characters in encrypted usernames and passwords.
Case:
Username: r&bgeorge
Password: tigger
We allow users to create usernames and passwords with special characters on the website. When we log them in, they have the option to save their login credentials for future logins.
User logs in and checks off the “remember your password” option. Then the user closes his browser and opens a new browser window for the application. The user is not logged in and the username field contains “r” only, which the letter before the special character. That’s where it breaks I assume. The password field is empty.
Code:
This is the class that does the encryption (method:EncodeString()):Imports System.Security
Imports System.IO
Imports System.Text
Imports Microsoft.VisualBasic
Public Class wwCrypto
'Set up the keys, these are used for both encryption and decryption
Private keyb() As Byte = {1, 253, 5, 50, 52, 91, 193, 133, 193, 121, 221, 164, 57, 128, 91, 91, 19, 39, 111, 197, 125, 98, 89, 48, 97, 154, 83, 187, 222, 167, 171, 74}
Private ivb() As Byte = {10, 61, 235, 120, 122, 120, 80, 248, 13, 182, 196, 212, 176, 46, 23, 85}
Public Function EncodeString(ByVal str As String) As String
Dim outStr As String
' Set up the streams and stuff
Dim ms As New MemoryStream()
Dim rv As New System.Security.Cryptography.RijndaelManaged()
Dim cs As New Cryptography.CryptoStream(ms, rv.CreateEncryptor(keyb, ivb), System.Security.Cryptography.CryptoStreamMode.Write)
Dim p() As Byte = Encoding.ASCII.GetBytes(str.ToCharArray())
Dim encodedBytes() As Byte
Try
cs.Write(p, 0, p.Length) ' write to stream as encrypted data
cs.FlushFinalBlock()
encodedBytes = ms.ToArray ' Convert the stream to something we can use
Catch ex As Exception
Finally
ms.Close()
cs.Close()
End Try
outStr = Convert.ToBase64String(encodedBytes)
Return outStr
End Function
Public Function DecodeString(ByVal str As String) As String
Dim outStr As String
Dim p() As Byte = Convert.FromBase64String(str)
Dim initialText(p.Length) As Byte
Dim rv As New System.Security.Cryptography.RijndaelManaged()
Dim ms As New MemoryStream(p)
Dim cs As New Cryptography.CryptoStream(ms, rv.CreateDecryptor(keyb, ivb), System.Security.Cryptography.CryptoStreamMode.Read)
Try
cs.Read(initialText, 0, initialText.Length)
cs.FlushFinalBlock()
Catch ex As Exception
Finally
ms.Close()
cs.Close()
End Try
Dim sb As New StringBuilder()
Dim i As Integer
Dim b As Byte
For i = 0 To initialText.Length() - 1
b = initialText(i)
If (b = 0) Then ' The encryption pads with NULLs, break so the aren't added to the string!
Exit For
End If
sb.Append(Convert.ToChar(b))
Next
Return sb.ToString()
End Function
End Class
Then we add this to the cookie.
Questions:
1. Is my reasoning correct and is the encryption mechanism preventing auto login for users with special characters?
2. What would be the possible solution? How can I encrypt special characters so they work?
Thanks.
Andrzej