Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rijndael in C#

Status
Not open for further replies.

domenu

Programmer
May 31, 2002
30
BE
Hi,

I need to encode a message with the Rijndael C++ classes found on the code project( and decode that encoded message
in a C#-appication.

Can anybody tell me what the correct implementation in C# is of that code project code? Of course using the existing .NET Security namespaces!

Thanks in advance,

nick;
 
here is an example that is working.
Code:
using System.Security.Cryptography;

// 
private ICryptoTransform encRij;
private ICryptoTransform enc3des;		
private ICryptoTransform decRij;
private ICryptoTransform dec3des;

// Helper functions
public static  string EncryptAndBase64(string val, ICryptoTransform trans)
{
	byte[] buf = UnicodeEncoding.Unicode.GetBytes(val);
	MemoryStream memStream = new MemoryStream();
	CryptoStream cryptStream = new CryptoStream(memStream, trans, CryptoStreamMode.Write);
          
	cryptStream.Write(buf, 0, buf.Length);
	cryptStream.FlushFinalBlock();
	cryptStream.Clear();
	Array.Clear(buf, 0, buf.Length);
	buf = memStream.GetBuffer();
	val =  Convert.ToBase64String(buf, 0, (int)memStream.Length);
	Array.Clear(buf, 0, (int)memStream.Length);
	return val;
}
public static string DecryptFromBase64(string base64str, ICryptoTransform trans)
{
	byte[] buf = Convert.FromBase64String(base64str);
	MemoryStream memStream = new MemoryStream();
	CryptoStream cryptStream = new CryptoStream(memStream, trans, CryptoStreamMode.Write);
	cryptStream.Write(buf, 0, buf.Length);
	cryptStream.FlushFinalBlock();
	cryptStream.Clear();
	Array.Clear(buf, 0, buf.Length);
	buf = memStream.GetBuffer();
		
	string ret = UnicodeEncoding.Unicode.GetString(buf, 0, (int)memStream.Length);
	Array.Clear(buf, 0, (int)memStream.Length);
	memStream.Close();
	return ret;
}
// Save a MemoryStream file with encryption to persistent file
public static void SaveData(MemoryStream memStream, ICryptoTransform ict, string filePath)
		{       try{
			FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, filePath);
			perm.Demand();
			}
			catch{
			}
			Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
			try
			{
				CryptoStream cryptStream = new CryptoStream(memStream, ict, CryptoStreamMode.Read);

				int read = 0;

				byte[] buf = new byte[4096];
				while (true)
				{
					read = cryptStream.Read(buf, 0, buf.Length);
					if (read == 0)
						break;
					fileStream.Write(buf, 0, read);
				}
				cryptStream.Clear();
			}
			finally
			{
				fileStream.Close();
			}
		}
// Load an ecrypted file and process it
private bool LoadData(string filePath, ICryptoTransform ict)
		{
			bool bReturn = true;
			if( FileExists(filePath) )
			{
				Stream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
				MemoryStream memStream = new MemoryStream();
				try
				{
					CryptoStream cryptStream = new CryptoStream(fileStream, ict, CryptoStreamMode.Read);
					int read = 0;
					byte[] buf = new byte[4096];

					while (true)
					{
						read = cryptStream.Read(buf, 0, buf.Length);
						if (read == 0)
							break;
						memStream.Write(buf, 0, read);
					}
					cryptStream.Clear();
					memStream.Position = 0;
					//
					// Process here the memStream file;
					// 
					buf = memStream.GetBuffer();
					Array.Clear(buf, 0, (int)memStream.Length);
					xmlr.Close();
					memStream.Close();
					
				}
				catch(Exception ex)
				{
					string sMsg = "LoadData:" + ex.GetType() + ex.Message;
					//Util.WriteToEventLog(sMsg,enumLogType.Error);
					bReturn = false;
				}
				finally
				{
					if (fileStream!=null)
					fileStream.Close();
				}
			}

private bool SetEncryptorDecryptor(Key3IV3 k3iv3)
{
	bool bReturn = true;
	RijndaelManaged aes = null;
	TripleDESCryptoServiceProvider des3 = null;
	try
	{
		aes = new RijndaelManaged();
		des3 = new TripleDESCryptoServiceProvider();
		encRij = aes.CreateEncryptor(k3iv3.KeyRij, k3iv3.IVRij);
		enc3des = des3.CreateEncryptor(k3iv3.Key3des, k3iv3.IV3des);
		decRij = aes.CreateDecryptor(k3iv3.KeyRij, k3iv3.IVRij);
		dec3des = des3.CreateDecryptor(k3iv3.Key3des, k3iv3.IV3des);
	}
	catch (Exception e)
	{   
		string sMsg = "SetEncryptorDecryptor:" + e.GetType() + e.Message;
		//Util.WriteToEventLog(sMsg,enumLogType.Error);
		bReturn = false;
	}
	finally
	{
		if (des3 != null)
		des3.Clear();
		if (aes != null)
		aes.Clear();
	}
	return bReturn;
			
}
// Provides the enc/dec objects from a given key
public class Key3IV3
	{
		private byte[] keyRij;
		private byte[] key3des;
		private byte[] ivRij;
		private byte[] iv3des;
		internal byte[] KeyRij
		{
			get { return keyRij; }
		}
		internal byte[] IVRij
		{
			get { return ivRij; }
		}
		internal byte[] Key3des
		{
			get { return key3des; }
		}
		internal byte[] IV3des
		{
			get { return iv3des; }
		}
		public Key3IV3(string txtPlainKey)
		{
			byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(txtPlainKey);
			SHA1 hash = new SHA1Managed();
			for (int i = 0; i < 200; ++i)
			{
				salt = hash.ComputeHash(salt, 0, salt.Length);
				hash.Initialize();
			}
			PasswordDeriveBytes pdb = new PasswordDeriveBytes(txtPlainKey, salt, "SHA512", 1000);
			Array.Clear(salt, 0, salt.Length);
			hash.Clear();

			keyRij = pdb.GetBytes(32);
			key3des = pdb.GetBytes(24);

			ivRij = pdb.GetBytes(16);
			iv3des = pdb.GetBytes(8);
	
		}
		public void Clear()
		{
			Array.Clear(keyRij, 0, keyRij.Length);
			Array.Clear(ivRij, 0, ivRij.Length);
			Array.Clear(key3des, 0, key3des.Length);
			Array.Clear(iv3des, 0, iv3des.Length);
		}
		~Key3IV3()
		{
			// ...
		}
	}

//How to use :
Code:
string sKeyUsedToEncryptDecrypt = "!blabla01#?";
key3iv3 = new Key3IV3(sKeyUsedToEncryptDecrypt );
SetEncryptorDecryptor(key3iv3);
key3iv3.Clear();
string txtToEncrypt = " This is an example of using RijndaelManaged and DES ...";
string txtEnc  = EncryptAndBase64(txtToEncrypt , enc3des);
string txtDec  = DecryptFromBase64(txtEnc  , dec3des);

//Encrypt a file using a MemoryStream  
MemoryStream memStream = new MemoryStream();
// Add data to memStream;
SaveData(memStream,encRij,"myfile.dat");   
byte[] buf = memStream.GetBuffer();
Array.Clear(buf, 0, (int)memStream.Length);
memStream.Close();

// Decrypt the file using a MemoryStream

LoadData("myfile.dat", decRij);
-obislavu-
 
Thanks obislavu,

I'll give it a try!

nick;
 
What about using the RijndaelManaged-class?

nick;
 
What about it? It's in there.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
This class is instantiated in the previous post in the SetEncryptorDecryptor() function.
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top