I am trying to encrypt and decrypt the password in ASP.NEt2.0 application with Rijndael
algo.
I am able to encrypt the password but not able to decrypt it.
Can anybody tell me what is the problem with my code,
I am pasting it here
public static string Encrypt(string StringToEncrypt, string Key)
{
Rijndael _encryptionservice = new RijndaelManaged();
ICryptoTransform _encryptor;
byte[] _bytesdata;
byte[] _byteskey;
string _encryptedstring;
Key = Key.ToLower();
_bytesdata = Encoding.ASCII.GetBytes(StringToEncrypt.PadRight(16));
_byteskey = Encoding.ASCII.GetBytes(Key.PadRight(32).Substring(0, 32));
_encryptionservice.Mode = CipherMode.CBC;
_encryptionservice.Key = _byteskey;
//_encryptionservice.IV = Encoding.ASCII.GetBytes("VIMSuitEncoding");
_encryptor = _encryptionservice.CreateEncryptor();
MemoryStream _memstreamencrypteddata = new MemoryStream();
CryptoStream encStream = new CryptoStream(_memstreamencrypteddata, _encryptor, CryptoStreamMode.Write);
try
{
encStream.Write(_bytesdata, 0, _bytesdata.Length);
}
catch (Exception ex)
{
throw new Exception("Error while writing encrypted data to the stream", ex);
}
encStream.FlushFinalBlock();
encStream.Close();
_encryptedstring = Convert.ToBase64String(_memstreamencrypteddata.ToArray());
return _encryptedstring;
}
public static string Decrypt(string StringToDecrypt, string Key)
{
Rijndael _encryptionservice = new RijndaelManaged();
byte[] _bytesdata;
byte[] _byteskey;
string _encryptedstring;
ICryptoTransform _decryptor;
int _decryptedstringlength;
Key = Key.ToLower();
_bytesdata = Convert.FromBase64String(StringToDecrypt);
_byteskey = Encoding.ASCII.GetBytes(Key.PadRight(32).Substring(0, 32));
_encryptionservice.Mode =CipherMode.CBC;
_encryptionservice.Key = _byteskey;
//_encryptionservice.IV = Encoding.ASCII.GetBytes("VIMSuitEncoding");
_decryptor = _encryptionservice.CreateDecryptor();
MemoryStream _memstreamencrypteddata = new MemoryStream(_bytesdata);
CryptoStream encStream = new CryptoStream(_memstreamencrypteddata, _decryptor, CryptoStreamMode.Read);
//_bytesdata = new byte[_bytesdata.Length];
try
{
_decryptedstringlength = encStream.Read(_bytesdata, 0, _bytesdata.Length);
}
catch (Exception ex)
{
throw new Exception("Error while writing encrypted data to the stream", ex);
}
encStream.Close();
//_encryptedstring = Convert.ToString(Encoding.ASCII.GetChars(_memstreamencrypteddata.ToArray())).Substring(0, _decryptedstringlength);
try
{
_encryptedstring = Convert.ToString(Encoding.ASCII.GetChars(_memstreamencrypteddata.ToArray())).Substring(0, _decryptedstringlength);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return _encryptedstring.Trim();
}
}