Background
It is very common that which cryptography algorithm is best for encryption and decryption. Because, everyone wants to secure his/her data, so that nobody can judge his/her data.
In cryptography algorithms, key plays an important role. If a weak key is used in the algorithm then everyone may decrypt his/her data. For judging any strong crypto algorithm, always checks "how much strong key is using." There are many examples of strong and weak keys of crypto algorithms like DES, Triple DES, and Rijndael.
- DES uses one 64-bit key
- Triple DES uses three 64-bit key
- Rijndael is used vary (128,160,192,224,256) bits keys
Key
Cryptography keys are divided into two areas. On the behalf of keys, cryptographic algorithms are also divided into two areas.
- Symmetric
- Asymmetric
Symmetric keys are used for data encryption/decryption. Those algorithms are used these keys are called Symmetric Cryptography Algorithms (Same key is used for both encryption and decryption). These keys are used for large size of data. E.g. DES, Rijndael.
And Asymmetric keys are used for symmetric keys encryption/decryption which is used for data encryption/decryption. In Asymmetric keys, two keys are used; private and public keys. Public key is used for encryption and private key is used for decryption. E.g. RSA, Digital Signatures.
Example
In my example, I am using Rijndael cryptography symmetric algorithm for data encryption/decryption and RSA cryptography asymmetric algorithm for Rijndael key's encryption/decryption. And key input is getting from a PWD file on random bases.
Encryption
I am encrypting file base large data. File data may be any size and any type (e.g. Image or text file). Rijndael is using CBC (Cipher Block Chaining) Mode. Block Size is 128-bits(standard block size) and key size is 256-bits which is dividing into two parts; key and IV (initial vector).
As you know, it is file based encryption/decryption; I am getting a file name as file input (e.g. abc.txt) and performing my Rijndael encryption algorithm and getting encrypted file with .enc extension. Encrypted file name is showing with current date and time with .enc extension (e.g. 911200191145.enc), which is showing encrypted file, as file output.
When you encrypt any data then you should secure that key, which is used for data encryption. For this purpose asymmetric key is used. I am securing my data key using RSA algorithm. Here RSA key size is 128-bytes. I am also generating my two pairs of keys; public and private key. Using Public key I am encrypting my data key and other one is public and private key pair ,which will send to other person, so that opposite person can decrypt my encrypted key using his public and private key.
You can send public key publicly. You may use FTP or other resources.
Embed Encrypted Key Into Encrypted Data.
Now I have encrypted data and key. But problem is how I can give my encrypted key to other side for decryption. For more securing my data I am embedding my encrypted key in the end of encrypted file. Now my Encryption process has completed.
Decryption
On other side, same process but in reverse order. I am getting .enc encrypted file and extracting all bytes and separating encrypted data and key. Using RSA private key, I am decrypting key. Now I have actual key through which I had encrypted my data. Now, I am getting encrypted key (e.g. 911200191145.enc) as file input and performing my Rijndael decryption algorithm and getting decrypted file with .dnc extension. Decrypted file name is showing with current date and time with .enc extension (e.g. 119200292512.dnc), which is showing decrypted file, as file output. Now, I have my actual data which I had encrypted.
Note:
Crypto Manager.zip contains definitions of Encryption and Decryption methods
- .enc extension for Encrypted File
- .dnc extension for Decrypted File
Encryption End
CryptoManager crm = null;
byte[] cryptoKey = null;
byte[] cryptoIV = null;
string[] line = new string[10];
string pwd = null;
#region Encryption Button
string encName = null;
string origName;
private void btnEnc_Click(object sender, EventArgs e)
{
try
{
DateTime current = DateTime.Now;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
byte[] keyToEncrypt;
byte[] encryptedKey;
origName = txtBrowse.Text;
encName = origName + ".dat";
try
{
crm.EncryptData(origName, encName, cryptoKey, cryptoIV);
FileInfo fi = new FileInfo(origName);
FileInfo fi2 = new FileInfo(encName);
//remove readonly attribute
if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
fi.Attributes &= ~FileAttributes.ReadOnly;
}
//copy creation and modification time
fi2.CreationTime = fi.CreationTime;
fi2.LastWriteTime = fi.LastWriteTime;
fi2.Attributes = FileAttributes.Normal | FileAttributes.Archive;
byte[] data = File.ReadAllBytes(encName);
//delete original file
File.Delete(encName);
#region write RSA (Public Private) key in xml files
StreamWriter writer = new StreamWriter("PublicPrivateKey.xml");
string publicprivatexml = RSA.ToXmlString(true);
writer.Write(publicprivatexml);
writer.Close();
#endregion
keyToEncrypt = System.Text.ASCIIEncoding.Unicode.GetBytes(pwd);
encryptedKey = RSA.Encrypt(keyToEncrypt, false);
//using (BinaryWriter bw = new BinaryWriter(File.Create(origName + " " + current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".enc")))
using (BinaryWriter bw = new BinaryWriter(File.Create(current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".enc")))
{
//Write data
bw.Seek(0, SeekOrigin.Begin);
bw.Write(data);
bw.Write(encryptedKey);
bw.Close();
}
MessageBox.Show("File Encrypted");
}
catch (CryptographicException ex)
{
MessageBox.Show(ex.Message);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (UnauthorizedAccessException ex)
{
//i.e. readonly
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
}
Decryption End
#region Decryption Button
private void btnDnc_Click(object sender, EventArgs e)
{
try
{
DateTime current = DateTime.Now;
string encName = txtBrowse.Text + "data" + ".enc";
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
#region Seperate key and data
byte[] alldata = File.ReadAllBytes(txtBrowse.Text);
byte[] getencryptedkey = new byte[128];
byte[] data = new byte[alldata.Length - 128];
for (int i = 0; i < alldata.Length - 128; i++)
{ data[i] = alldata[i]; }
for (int i = alldata.Length - 128, j = 0; i < alldata.Length; i++, j++)
{ getencryptedkey[j] = alldata[i]; }
using (BinaryWriter bw = new BinaryWriter(File.Create(encName)))
{
bw.Write(data);
bw.Close();
}
#endregion
#region key decryption
StreamReader reader = new StreamReader("PublicPrivateKey.xml");
string publicprivatekeyxml = reader.ReadToEnd();
RSA.FromXmlString(publicprivatekeyxml);
reader.Close();
byte[] decryptedKey = RSA.Decrypt(getencryptedkey, false);
pwd = System.Text.ASCIIEncoding.Unicode.GetString(decryptedKey);
byte[] dk = null;
byte[] div = null;
crm.getKeysFromPassword(pwd, out dk, out div);
cryptoKey = dk;
cryptoIV = div;
#endregion
string ext = Path.GetExtension(encName).ToLower();
if (ext != ".enc")
{
MessageBox.Show("Please Enter correct File");
return;
}
string dncName = Path.GetDirectoryName(encName) + "\\" + Path.GetFileNameWithoutExtension(encName);
dncName = current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".dnc";
try
{
if (crm.DecryptData(encName, dncName, cryptoKey, cryptoIV))
{
FileInfo fi = new FileInfo(encName);
FileInfo fi2 = new FileInfo(dncName);
if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{ fi.Attributes &= ~FileAttributes.ReadOnly; }
//copy creation and modification time
fi2.CreationTime = fi.CreationTime;
fi2.LastWriteTime = fi.LastWriteTime;
//delete encrypted file
File.Delete(encName);
MessageBox.Show("File Decrypted");
}
else
{
MessageBox.Show("The file can't be decrypted - probably wrong password");
}
}
catch (CryptographicException ex)
{ MessageBox.Show(ex.Message); }
catch (IOException ex)
{ MessageBox.Show(ex.Message); }
catch (UnauthorizedAccessException ex)
{ //i.e. readonly
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
}
#endregion
Random Bases PWD
pwd = "abcdefhz";
//get keys from password
byte[] dk = null;
byte[] div = null;
crm.getKeysFromPassword(pwd, out dk, out div);
cryptoKey = dk;
cryptoIV = div;
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
this.Close();
return;
}
samir parimalPosted Apr 29, 2016, 6:48 AM
Hi, How to play .enc video file, Please reply.
Ram kPosted Jun 29, 2015, 3:23 PM
Hi, when I tested this code I get Bad data error on decryption part on line byte[] decryptedKey = RSA.Decrypt(getencryptedkey, false); Using VS 2013. Any help appreciated. Thanks.
mishael vayanPosted Apr 16, 2015, 7:01 AM
Hi...I have some question,I want to decrypt video file from video ,it means that I save the encrypted video on dvd and when I click on encrypted video file ,It decrypt video file and show it without save it in hard disk.....please help Me.
Muhammad ShakirPosted Sep 4, 2013, 10:20 AM
@Adura Aziz... Sorry replying very late after two years.. Replying in case useful for new programmers. Encrypted and Decrypted files are saved in Application debug folder. It is is just path issue.
sunil polPosted Aug 13, 2012, 2:51 AM
Hi..! i want to ecrypt file in c or c++ and decrypt it in c#.vice versa.what should i do?
adura azizPosted Dec 25, 2011, 9:42 AM
hello shakir...why the file is not encrypted even though the window popup appear saying "file encrypt"
adura azizPosted Dec 25, 2011, 5:03 AM
Hello Muhammad Syakir... i wanna ask u ...abou encrypt file using rinjdael.... after the file have been encrypted, where does the file encrypted will store??.. coz...when i'm try running this application.. the state of file i'm trying to encrypt does not encrypted..still in plaintext state...
ahmed bashirPosted Oct 26, 2011, 2:54 AM
Hello Mohamed when i encrypt image file ,I get encrypt without any problem but i need to get encrypt image file thank you
Indranil PaulPosted Aug 8, 2011, 6:36 AM
This is very very helpful .... codes are simple but effective. Thank you
GaneshPosted Oct 5, 2010, 8:04 AM
Hi Muhammad, Your article is nice, I need your help (Using RSA to encrypt and Decrypt a file) in this. Waiting for your reply. Thanks Ganesh
mohit mahajanPosted Jul 13, 2010, 1:08 AM
Dear sir ,i have some iso format file (finger prints)i want to decrpt these file will you plzz guide me how i can decrpt tht files thanks & regards mohit
Richard BuffingtonPosted Jul 5, 2010, 5:53 PM
Do you have any example on how to use the Event Handler that you included in your program? As far as I can tell it is left unused. Thanks.
iyad shaheenPosted May 15, 2010, 9:40 PM
help -i need to calculate hash every block of cipher for while true that you using ,to using calculate sha1 conect me : [email protected]
hari prasadPosted Dec 26, 2009, 9:23 PM
hi sir, can we able to encrypt an XML file using this program??
ravi sankar tekuruPosted Oct 16, 2009, 7:49 AM
Showing error at CryptoManager crm = null; which namespace it comes under.I implemented namespaces using System.Security;using System.Security.Cryptography; provide the download by resolving error.I am getting error while extracting the zip file ! F:\CryptoManager.rar: Unknown method in Crypto Manager.cs ! F:\CryptoManager.rar: No files to extract
Arun KumarPosted Sep 17, 2009, 6:28 AM
Pls upload new zip file.. The file is empty
mmm bbbPosted Oct 4, 2008, 2:24 PM
i want c++ code for implement Encrypt a file using Rijndael
RaymondPosted Sep 2, 2008, 12:05 AM
Hey, the attached file, Crypto Manager.zip is reporting as corrupt on both Linux and Windows.
RaymondPosted Sep 2, 2008, 12:05 AM
Hey, the attached file, Crypto Manager.zip is reporting as corrupt on both Linux and Windows.
mandy moorePosted Feb 15, 2008, 4:42 AM
I'm beginner for encryption, and hope to get ur reply soon. i wan to encrypt file hash value with private key and then encrypt it again with user public key. How i going code it?Thanks.