Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

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

, 4 Jul 2004
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

Share

About the Author

vcepa

Germany Germany
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141220.1 | Last Updated 5 Jul 2004
Article Copyright 2004 by vcepa
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid