5
Reply

Encoding and Decoding Password in login Form from Database

Nilesh Jadav

Nilesh Jadav

Sep 12 2016 8:57 AM
353
I am making a Registration and a login Form with encoded password saved to database, I can encode the password using encodin.utf8.
 
Problem is I register with some username and password and the data get saved to database with encoded password, but when I login with the same data it shows me this below error. 

Invalid length for a Base-64 char array or string.

 
Can anyone give me the described solution for this.  Below I am attaching my encoded and decoded methods :
 
 
Encoded :
 
 
  1. private string encryption(string clearText)  
  2.    {  
  3.   
  4.        string encryptkey = "123";  
  5.        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);  
  6.        using (Aes encrypt = Aes.Create())  
  7.        {  
  8.   
  9.   
  10.            Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(encryptkey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });  
  11.            encrypt.Key = rdb.GetBytes(32);  
  12.            encrypt.IV = rdb.GetBytes(16);  
  13.   
  14.            using (MemoryStream ms = new MemoryStream())  
  15.            {  
  16.   
  17.                using (CryptoStream cst = new CryptoStream(ms, encrypt.CreateEncryptor(), CryptoStreamMode.Write))  
  18.                {  
  19.                    cst.Write(clearBytes, 0, clearBytes.Length);  
  20.                    cst.Close();  
  21.                }  
  22.   
  23.                clearText = Convert.ToBase64String(ms.ToArray());  
  24.   
  25.            }  
  26.   
  27.        }  
  28.   
  29.   
  30.        return clearText; 
 
 
 
Decoded :
 
 
 
  1. private string decryp(string cipherText)  
  2. {  
  3.   
  4. cipherText = cipherText.Replace(" ""+");  
  5. string decryptkey = "123";  
  6. byte[] cipherBytes = Convert.FromBase64String(cipherText.Replace(" ""+"));  
  7. using (Aes encrypt = Aes.Create())  
  8. {  
  9.   
  10. Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(decryptkey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });  
  11. encrypt.Key = rdb.GetBytes(32);  
  12. encrypt.IV = rdb.GetBytes(16);  
  13.   
  14.   
  15. using (MemoryStream ms = new MemoryStream())  
  16. {  
  17.   
  18. using (CryptoStream cst = new CryptoStream(ms, encrypt.CreateDecryptor(), CryptoStreamMode.Write))  
  19. {  
  20.   
  21. cst.Write(cipherBytes, 0, cipherBytes.Length);  
  22. cst.Close();  
  23.   
  24. }  
  25.   
  26. cipherText = Encoding.Unicode.GetString(ms.ToArray());  
  27.   
  28. }  
  29.   
  30. }  
  31.   
  32. return cipherText; 


 
 
Any help will be appreciated,thank you !
 

Answers (5)