Snapshot for text encryption/decryption using the secret key
Snapshot for file encryption using the secret key
Snapshot for decryption using the secret key
Introduction
I found a lot of articles in many sites, even many articles on CodeProject itself. An article Encrypt <--> Decrypt Data with C# written by Syed Moshiur Murshed is based on MD5CryptoServiceProvider
class and it describes the encrypting/decrypting of text. I did nothing special. I was working on custom functoid for BizTalk Server 2006. Then I came across the problem with encryption of string and got the solution in this way.
Cryptography Classes
We have a number of cryptography classes which are used to encrypt and decrypt the data under the using System.Security.Cryptography namespace, e.g. DESCryptoServiceProvider
class, DSACryptoServiceProvider
, MD5CryptoServiceProvider
, RNGCryptoServiceProvider
, RSACryptoServiceProvider
, SHA1CryptoServiceProvider
, TripleDESCryptoServiceProvider
blah! blah! Each has its own algorithm. So there are many ways to encrypt/decrypt data by using any of the cryptography classes. To know more about cryptography, click here.
Using the Code
In this sample project, I have two types of encryption/decryption:
- Encryption/decryption of string using secret key
- Encryption/decryption of file using secret key
The code itself is self descriptive. There is nothing special which needs to be explained.
Overview
This is the simple example of encrypting/decrypting of any kind of file, data or string object. you can customize it in your own way. Here I have used the Transform()
method. It works in two different ways:
- If you want to encrypt/decrypt a small size of string, data, or files then in this case you can pass byte array as input. So before calling this method, you will have to convert input object into byte array.
- If you want to encrypt/decrypt any big file like avi, Word document, mpg file, then you will have to pass input as
null
, but you have to specify an input and output file name with complete path.
private byte[] Transform(byte[] input, TransformType transformType)
{
CryptoStream cryptoStream = null;
RijndaelManaged rijndael = null;
ICryptoTransform rijndaelTransform = null;
FileStream fsIn = null;
FileStream fsOut = null;
MemoryStream memStream = null;
try
{
rijndael = new RijndaelManaged();
rijndael.Key = this._Key;
rijndael.IV = this._IV;
if (transformType == TransformType.ENCRYPT)
{
rijndaelTransform = rijndael.CreateEncryptor();
}
else
{
rijndaelTransform = rijndael.CreateDecryptor();
}
if ((input != null) && (input.Length > 0))
{
memStream = new MemoryStream();
cryptoStream = new CryptoStream(
memStream, rijndaelTransform, CryptoStreamMode.Write);
cryptoStream.Write(input, 0, input.Length);
cryptoStream.FlushFinalBlock();
return memStream.ToArray();
}
else if ((_inputFile.Length > 0) && (_outputFile.Length > 0))
{
fsIn = new FileStream(_inputFile,
FileMode.Open, FileAccess.Read);
fsOut = new FileStream(_outputFile,
FileMode.OpenOrCreate, FileAccess.Write);
cryptoStream = new CryptoStream(
fsOut, rijndaelTransform, CryptoStreamMode.Write);
int bufferLen = 4096;
byte[] buffer = new byte<bufferlen />;
int bytesRead;
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cryptoStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
cryptoStream.FlushFinalBlock();
}
return null;
}
catch (CryptographicException)
{
throw new CryptographicException(
"Password is invalid. Please verify once again.");
}
finally
{
if (rijndael != null) rijndael.Clear();
if (rijndaelTransform != null) rijndaelTransform.Dispose();
if (cryptoStream != null) cryptoStream.Close();
if (memStream != null) memStream.Close();
if (fsOut != null) fsOut.Close();
if (fsIn != null) fsIn.Close();
}
}
Here you can see the complete class with name EncryptDecrypt.cs. See the code below:
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace EncryptDecrypt
{
public class MyEncryptor
{
private string _Phrase = "";
private string _inputFile = "";
private string _outputFile = "";
enum TransformType { ENCRYPT = 0, DECRYPT = 1 }
public string Phrase
{
set
{
this._Phrase = value;
this.GenerateKey(this._Phrase);
}
}
private byte[] _IV;
private byte[] _Key;
public MyEncryptor(string SecretPhrase)
{
this.Phrase = SecretPhrase;
}
public string Encrypt(string EncryptValue)
{
try
{
if (EncryptValue.Length > 0)
{
byte[] input = Encoding.UTF8.GetBytes(EncryptValue);
return (Convert.ToBase64String(Transform(input,
TransformType.ENCRYPT)));
}
else
{
return "";
}
}
catch (Exception ex)
{
throw ex;
}
}
public string Decrypt(string DecryptValue)
{
try
{
if (DecryptValue.Length > 0)
{
byte[] input = Convert.FromBase64String(DecryptValue);
return (Encoding.UTF8.GetString(Transform(input,
TransformType.DECRYPT)));
}
else
{
return "";
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Encrypt(string InputFile, string OutputFile)
{
try
{
if ((InputFile != null) && (InputFile.Length > 0))
{
_inputFile = InputFile;
}
if ((OutputFile != null) && (OutputFile.Length > 0))
{
_outputFile = OutputFile;
}
Transform(null, TransformType.ENCRYPT);
}
catch (Exception ex)
{
throw ex;
}
}
public void Decrypt(string InputFile, string OutputFile)
{
try
{
if ((InputFile != null) && (InputFile.Length > 0))
{
_inputFile = InputFile;
}
if ((OutputFile != null) && (OutputFile.Length > 0))
{
_outputFile = OutputFile;
}
Transform(null, TransformType.DECRYPT);
}
catch (Exception ex)
{
throw ex;
}
}
private void GenerateKey(string SecretPhrase)
{
this._Key = new byte[24];
this._IV = new byte[16];
byte[] bytePhrase = Encoding.ASCII.GetBytes(SecretPhrase);
SHA384Managed sha384 = new SHA384Managed();
sha384.ComputeHash(bytePhrase);
byte[] result = sha384.Hash;
for (int loop = 0;
loop < 24; loop++) this._Key[loop] = result[loop];
for (int loop = 24;
loop < 40; loop++) this._IV[loop - 24] = result[loop];
}
private byte[] Transform(byte[] input, TransformType transformType)
{
CryptoStream cryptoStream = null;
RijndaelManaged rijndael = null;
ICryptoTransform rijndaelTransform = null;
FileStream fsIn = null;
FileStream fsOut = null;
MemoryStream memStream = null;
try
{
rijndael = new RijndaelManaged();
rijndael.Key = this._Key;
rijndael.IV = this._IV;
if (transformType == TransformType.ENCRYPT)
{
rijndaelTransform = rijndael.CreateEncryptor();
}
else
{
rijndaelTransform = rijndael.CreateDecryptor();
}
if ((input != null) && (input.Length > 0))
{
memStream = new MemoryStream();
cryptoStream = new CryptoStream(
memStream, rijndaelTransform,
CryptoStreamMode.Write);
cryptoStream.Write(input, 0, input.Length);
cryptoStream.FlushFinalBlock();
return memStream.ToArray();
}
else if ((_inputFile.Length > 0) && (_outputFile.Length > 0))
{
fsIn = new FileStream(_inputFile,
FileMode.Open, FileAccess.Read);
fsOut = new FileStream(_outputFile,
FileMode.OpenOrCreate, FileAccess.Write);
cryptoStream = new CryptoStream(
fsOut, rijndaelTransform, CryptoStreamMode.Write);
int bufferLen = 4096;
byte[] buffer = new byte<bufferlen />;
int bytesRead;
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cryptoStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
cryptoStream.FlushFinalBlock();
}
return null;
}
catch (CryptographicException)
{
throw new CryptographicException(
"Password is invalid. Please verify once again.");
}
finally
{
if (rijndael != null) rijndael.Clear();
if (rijndaelTransform != null) rijndaelTransform.Dispose();
if (cryptoStream != null) cryptoStream.Close();
if (memStream != null) memStream.Close();
if (fsOut != null) fsOut.Close();
if (fsIn != null) fsIn.Close();
}
}
}
}