Only part of the string is getting decrypted, i think it has to do with my encoding.
Here is what happens:
string s = \"The brown fox jumped
Here you go:
string s = "The brown fox jumped over the green frog";
string k = "urieurut";
byte[] enc = EncryptString(s, k);
string dec = DecryptString(enc, k);
You can't attempt to interpret an encrypted bunch of bytes as a Unicode string. Keep them as bytes. The decrypted version can be converted back to string.
Also note the disposing of disposable objects below. You could wind up with some resources being held too long or leak if you don't release them properly with using()
or Dispose()
.
public static byte[] EncryptString(string stringToEncrypt, string encryptionKey)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
using (RijndaelManaged RMCrypto = new RijndaelManaged())
using (MemoryStream ms = new MemoryStream())
using (ICryptoTransform encryptor = RMCrypto.CreateEncryptor(key, key))
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
byte[] encryptedString = UE.GetBytes(stringToEncrypt);
cs.Write(encryptedString, 0, encryptedString.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
public static string DecryptString(byte[] stringToDecrypt, string encryptionKey)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(encryptionKey);
using (RijndaelManaged RMCrypto = new RijndaelManaged())
using (MemoryStream ms = new MemoryStream())
using (ICryptoTransform decryptor = RMCrypto.CreateDecryptor(key, key))
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
{
cs.Write(stringToDecrypt, 0, stringToDecrypt.Length);
cs.FlushFinalBlock();
return UE.GetString(ms.ToArray());
}
}