Hi,
I've written an encryption/decryption class that uses the methods below to decrypt and encrypt strings. This works fine, until I save the encrypted string to my SQL Server database. It saves in the database like this: '??????????????????' and cannot then be decrypted. I assume it's because I'm using Unicode encoding in my encryption/decryption methods, but if I change it to ASCII encoding the DesDecrypt method won't work. Can anyone help?
I've written an encryption/decryption class that uses the methods below to decrypt and encrypt strings. This works fine, until I save the encrypted string to my SQL Server database. It saves in the database like this: '??????????????????' and cannot then be decrypted. I assume it's because I'm using Unicode encoding in my encryption/decryption methods, but if I change it to ASCII encoding the DesDecrypt method won't work. Can anyone help?
Code:
public static string DesEncrypt(string stringToEncrypt, string hashString)
{
byte[] data = ConvertStringToByteArray(stringToEncrypt);
string pws = hashString;
System.Security.Cryptography.PasswordDeriveBytes db = new System.Security.Cryptography.PasswordDeriveBytes(pws, new byte[0]);
byte[] m_bDESKey= db.GetBytes(16);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Mode = CipherMode.CBC;
byte[] m_bDESIV = System.Text.UnicodeEncoding.Unicode.GetBytes(hashString);
MemoryStream ms = new MemoryStream(4096);
CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(KEY192, IV192), CryptoStreamMode.Write);
encStream.Write(data,0,data.Length);
encStream.FlushFinalBlock();
//calculate the length of the encrypted data
byte[] bResult = new byte[ms.Position];
ms.Position = 0;
ms.Read(bResult, 0, bResult.Length) ;
encStream.Close();
return System.Text.UnicodeEncoding.Unicode.GetString(bResult);
}
public static string DesDecrypt(string stringToDeCrypt, string hashString)
{
byte[] data = ConvertStringToByteArray(stringToDeCrypt);
string pws = hashString;
System.Security.Cryptography.PasswordDeriveBytes db = new System.Security.Cryptography.PasswordDeriveBytes(pws, new byte[0]);
byte[] m_bDESKey= db.GetBytes(16);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Mode = CipherMode.CBC;
byte[] m_bDESIV = System.Text.UnicodeEncoding.Unicode.GetBytes(hashString);
MemoryStream ms = new MemoryStream(data.Length);
CryptoStream encStream = new CryptoStream(ms, des.CreateDecryptor(KEY192, IV192), CryptoStreamMode.Read);
ms.Write(data,0,data.Length);
ms.Position = 0;
string strResult = new StreamReader(encStream).ReadToEnd();
encStream.Close();
return strResult;
}
private static Byte[] ConvertStringToByteArray(String s)
{
Byte[] returnValue = System.Text.UnicodeEncoding.Unicode.GetBytes(s);
return returnValue;
}