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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

string encryption 2

Status
Not open for further replies.
it depends entirely on what sort of encryption you need. do you need one way encryption (often used for passwords) - this means that you will have the encrypted password and you will compare this to the encrypted text that the user enetered as password and if they match, it's a correct entry, but you won't be able to ever see the password, meaning you can't decrypt it - e.g. MD5
or do you need two ways encryption - which means that if you know the key with which the string has been encrypted, you can decrypt it again. this sort of algorithms also divide in two types : symmetrical key algorithms (DES, 3DES) or asymmetrical key algorithms.

the symmetrical key algorythms use the sam key to encrypt and to decrypt the data
the asymmetrical key algorythms use one key to encrypt (usually the private key of the sender and the public key of the receiver) and another to decrypt (usually the public key of the sender and the private key of the receiver)

depending on all this you should narrow the search criteria

--------------------------
"two wrongs don't make a right, but three lefts do" - the unknown sage
 
DaZZleD is correct -- a lot depends on your intended use.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
I agree with DaZZleD post.
I put here an example in thinking that you can find something to reuse.
I put here some classes that may will help you:
Code:
// The bytes encapsulated here will be used by RijndaelManaged and TripleDESCryptoServiceProvider objects
//They are created from a plain string passed in the constructor ( key that you provide and use to encrypt and decrypt)
//It is the responsability of the client of this class to destroy that key after this object is created.
// Call Clear() when finished with an object of Key3IV3 type. 
using System;
using System.Security.Cryptography;

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 txtPlain)
{
	byte[] salt = System.Text.UTF8Encoding.UTF8.GetBytes(txtPlain);
	SHA1 hash = new SHA1Managed();
	for (int i = 0; i < 200; ++i)
	{
		salt = hash.ComputeHash(salt, 0, salt.Length);
		hash.Initialize();
	}
	PasswordDeriveBytes pdb = new PasswordDeriveBytes(txtPlain, 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()
{
}

Here are functions to encrypt and decript a string using RijndaelManaged (SymmetricAlgorithm) and TripleDESCryptoServiceProvider classes

Code:
using System;
using System.IO;
using System.Text;
using System.Security.Permissions;
using System.Security.Cryptography;
public class Util
{
	public Util()
	{
	}
	// Encrypt a string
	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;
	}
	// Decrypt an encrypted string 
	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;
	}
	// Encrypt to File 
	public static void Encrypt2File(MemoryStream memStream, ICryptoTransform ict, string filePath)
	{
		FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, filePath);
		perm.Demand();
		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();
		}
	}
}


How to use ?

Code:
/// Encryption objects
ICryptoTransform encRij;
ICryptoTransform enc3des;		
ICryptoTransform decRij;
ICryptoTransform dec3des;
//...
Key3IV3 k3iv3 = new Key3IV3("string key you should to provide and will be used by encrypt/decrypt processes");
RijndaelManaged 		aes = null; 		//SymmetricAlgorithm
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 = "...Error ..." + e.GetType() + e.Message;
	//Util.WriteToEventLog(sMsg);
	
}
finally
{
	if (des3 != null)
		des3.Clear();
	if (aes != null)
		aes.Clear();
}

string encName =  Util.EncryptAndBase64(dlg.Name, enc3des);
string encSSN  = Util.EncryptAndBase64(dlg.SSN, enc3des);

//
string decName = Util.EncryptAndBase64(encName, dec3des);
string decSSN  = Util.DecryptFromBase64(encSSN, dec3des);

// Fill a MemoryStream object using a XmlTextWriter to populate it
// or other method 
MemoryStream memStream = new MemoryStream();
XmlTextWriter xtw = new XmlTextWriter(memStream, null);

// ... Fill here the memStream object with encrypted encName, encSSN

Util.Encrypt2File(memStream,encRij, "myfile.dat");
byte[] buf = memStream.GetBuffer();
Array.Clear(buf, 0, (int)memStream.Length);
xtw.Flush();
xtw.Close();
memStream.Close();

// Read from encrypted file into MemoryStream using decRij 

try
{
	Stream fileStream = new FileStream("myfile.dat", FileMode.Open, FileAccess.Read, FileShare.None);
	MemoryStream memStream = new MemoryStream((int)fileStream.Length);
	CryptoStream cryptoStream = new CryptoStream(fileStream, decRij, CryptoStreamMode.Read);
	byte[] buf = new byte[4096];
	int read = 0;
	while(true)
	{
		read = cryptoStream.Read(buf, 0, buf.Length);
		if(read == 0)
			break;
		memStream.Write(buf, 0, read);
	}
	cryptoStream.Clear();
	fileStream.Close();
	fileStream = null;
	memStream.Position = 0;
}
catch (Exception ex)
{
}

//...

encRij.Dispose();
enc3des.Dispose();
decRij.Dispose();
dec3des.Dispose();
k3iv3.Clear();

-obislavu-
 
Interesting...a bit too advanced for me at the moment, but still interesting! I have one question regarding keys - can I put whatever characters I want into my key or do they need to be within a certain ASCII range?


Thanks,

Mike
 
With regard to keys, can I use whatever characters I want, or do you need to stick with a certain range of ASCII values?


Thanks,

Mike
 
Thanks Obislavu


Cheers,

Mike

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top