This is a method, for encrypting a text and returning the cipher text:
public static string Encrypt(this string clearText, CryptologyMethod method)
{
ICryptoTransform cryptoTransform = null;
switch (method)
{
case CryptologyMethod.TripleDes:
cryptoTransform = new TripleDESCryptoServiceProvider().CreateEncryptor(Config.TripleDesKey, Config.TripleDesIV);
break;
case CryptologyMethod.AES:
cryptoTransform = new AesCryptoServiceProvider().CreateEncryptor(Config.AesKey, Config.AesIV);
break;
}
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(clearText);
cryptoStream.FlushFinalBlock();
return memoryStream.Text();
}
}
}
}
public enum CryptologyMethod
{
TripleDes,
AES
}
Text() is an extension method, to read the content of a stream:
public static string Text(this Stream stream)
{
return new StreamReader(stream).ReadToEnd();
}
Also, Config.TripleDesKey and other properties return array of bytes read from configuration file.
The problem is that when I use this extension method, the result is always an empty string:
string cipherText = “some clear text”.Encrypt(CryptologyMethod.TripleDes);
// cipherText is empty
I think I’ve had that issue before, the solution was pretty obvious once I figured it out and completely opaque before then.
The problem was that ReadToEnd is relative, as in “from current location to end”. The problem being that “current position” already WAS “end” because I’d just finished writing to the end of the stream. So I would fix your problem like this:
Worked for me with a similar issue, hope it helps.