Click here to Skip to main content
15,896,529 members
Articles / Programming Languages / C#

A CBC Stream Cipher in C# (With wrappers for two open source AES implementations in C# and C)

Rate me:
Please Sign up or sign in to vote.
4.54/5 (19 votes)
4 Jul 200412 min read 150.2K   3.7K   56  
An article on .NET cryptography
using System;

namespace sc
{
	/// <summary>
	/// make a key out of a password
	/// </summary>
	public sealed class KeyGen
	{
		private KeyGen()
		{}

		/// <summary>
		/// safe method to generate a key
		/// see the next override for more info
		/// </summary>
		public static byte[] DeriveKey(string password, int keySize, byte[] salt)
		{
			return DeriveKey(password, keySize, salt, 1024);
		}

		/// <summary>
		/// make a key out of a string password
		/// based on PBKDF1 (PKCS #5 v1.5)
		/// see http://www.faqs.org/rfcs/rfc2898.html
		/// if you do not want a salt set it to null
		/// recomended salt length must be between 8 and 16 bytes
		/// This implementation support keySize up to 32 bytes
		/// use salt = null, iterationCount = 1 for minimal strength
		/// </summary>
		public static byte[] DeriveKey(string password, int keySize, byte[] salt, int iterationCount)
		{
			if(keySize > 32) keySize = 32;
			byte[] data = ASCIIEncoder(password);
			if(salt != null)
			{
				byte[] temp = new byte[data.Length + salt.Length];
				Array.Copy(data, 0, temp, 0, data.Length);
				Array.Copy(salt, 0, temp, data.Length, salt.Length);
				data = temp;
			}
			if(iterationCount <= 0) iterationCount = 1;
			for(int i = 0; i < iterationCount; i++)
			{
				data = SHA256.MessageSHA256(data);
			}
			byte[] key = new byte[keySize];
			Array.Copy(data, 0, key, 0, keySize);
			return key;
		}

		/// <summary>
		/// helper function not to rely on System.Text.ASCIIEncoder
		/// </summary>
		public static byte[] ASCIIEncoder(string s)
		{
			byte[] ascii = new byte[s.Length];
			for(int i = 0; i < s.Length; i++)
			{
				ascii[i] = (byte)s[i];
			}
			return ascii;
		}

	}//EPC
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions