I am trying to understand simple codes of TripleDES encryption to see how it works. And I have seen many codes on google. Some of them used TripleDES class and some of them used TripleDESCryptoServiceProvider class. All I know, the second one is inherited from the first one.
TripleDES class:(showing only the encrption part)
static void Main(string[] args)
{
TripleDES TripleDESalg = TripleDES.Create("TripleDES");
string sData = "Here is some data to encrypt.";
byte[] Data = EncryptTextToMemory(sData, TripleDESalg.Key, TripleDESalg.IV);
string Final = DecryptTextFromMemory(Data, TripleDESalg.Key, TripleDESalg.IV);
Console.WriteLine(Final);
Console.ReadLine();
}
public static byte[] EncryptTextToMemory(string Data, byte[] Key, byte[] IV)
{
MemoryStream mStream = new MemoryStream();
TripleDES tripleDESalg = TripleDES.Create();
CryptoStream cStream = new CryptoStream(mStream, tripleDESalg.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
byte[] ret = mStream.ToArray();
cStream.Close();
mStream.Close();
return ret;
}
And the TripleDESCryptoServiceProvider class: (only the encryption code)
static void Main(string[] args)
{
TripleDESCryptoServiceProvider tDESalg = new TripleDESCryptoServiceProvider();
string sData = "Here is some data to encrypt.";
byte[] Data = EncryptTextToMemory(sData, tDESalg.Key, tDESalg.IV);
string Final = DecryptTextFromMemory(Data, tDESalg.Key, tDESalg.IV);
Console.WriteLine(Final);
Console.ReadLine();
}
public static byte[] EncryptTextToMemory(string Data, byte [] key, byte[] iv)
{
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream,
new TripleDESCryptoServiceProvider().CreateEncryptor(key, iv ),
CryptoStreamMode.Write);
byte[] toEncrypt = new ASCIIEncoding().GetBytes(Data);
cStream.Write(toEncrypt, 0, toEncrypt.Length);
cStream.FlushFinalBlock();
byte[] ret = mStream.ToArray();
cStream.Close();
mStream.Close();
return ret;
}
Both of the codes work fine and 99% same. But my question is,
What is the difference between these two classes?
Which class is more acceptable?
What is the difference between TransformFinalBlock() and FlushFinalBlock()?
There are codes without using MemoryStream and CryptoStream classes. And they works great. So what is the benefit of using these streams?
And last, in the above code how will I know what keysize, cyphermode and padding algorithm is used?
Thanks in advance.