Archive for March, 2005

Encryption in .NET Framework is a little tricky… not just create an object and call Encrypt and Decrypt methods, but terms like CryptoServiceProvider, CipherMode, IV and so on…Most of the examples that i found on the internet treats file encryption instead of text encryption (which i’m interested in).
These days i found a very useful article about text encryption written by Chidi C. Ezeukwu. Based on it i wrote a class for encryption/decryption with RC2 algorythm. This class can be used stand-alone in the application or as an assembly.

An archive that contains the VS.NET project for the assembly is available here: .NET rc2 Encryption assembly project
The compiled DLL assembly zipped is available here: .NET rc2 Encryption DLL assembly

The class code is the following:

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace webxpert
        {
                public class wx_crypt
                {
                        #region Variables
                        private string mKey = string.Empty;
                        private string mSalt = string.Empty;
                        private SymmetricAlgorithm mCryptoService;
                        #endregion

                        #region Properties
                        public string Key
                        {
                                get
                                {
                                        return mKey;
                                }
                                set
                                {
                                        mKey = value;
                                }
                        }

                        public string Salt
                        {
                                // Salt value
                                get
                                {
                                        return mSalt;
                                }
                                set
                                {
                                        mSalt = value;
                                }
                        }

                        #endregion

                        #region Constructor
                        public wx_crypt()
                        {
                                mCryptoService = new RC2CryptoServiceProvider();
                                mCryptoService.IV = new byte[] {0xf, 0x6f, 0x13, 0x2e, 0x35, 0xc2, 0xcd, 0xf9};
                                mCryptoService.Mode = CipherMode.CBC;
                        }

                        #endregion

                        #region Methods
                        public virtual byte[] GetLegalKey()
                        {
                                // Adjust key if necessary, and return a valid key
                                if (mCryptoService.LegalKeySizes.Length > 0)
                                {
                                        // Key sizes in bits
                                        int keySize = mKey.Length * 8;
                                        int minSize = mCryptoService.LegalKeySizes[0].MinSize;
                                        int maxSize = mCryptoService.LegalKeySizes[0].MaxSize;
                                        int skipSize = mCryptoService.LegalKeySizes[0].SkipSize;
                               
                                        if (keySize > maxSize)
                                        {
                                                // Extract maximum size allowed
                                                mKey = mKey.Substring(0, maxSize / 8);
                                        }
                                        else if (keySize < maxSize)
                                        {
                                                // Set valid size
                                                int validSize = (keySize <= minSize)? minSize : (keySize – keySize % skipSize) + skipSize;
                                                if (keySize < validSize)
                                                {
                                                        // Pad the key with asterisk to make up the size
                                                        mKey = mKey.PadRight(validSize / 8, ‘*’);
                                                }
                                        }
                                }
                                PasswordDeriveBytes key = new PasswordDeriveBytes(mKey, ASCIIEncoding.ASCII.GetBytes(mSalt));
                                return key.GetBytes(mKey.Length);
                        }

                        public virtual string Encrypt(string plainText)
                        {
                                byte[] plainByte = ASCIIEncoding.ASCII.GetBytes(plainText);
                                byte[] keyByte = GetLegalKey();

                                // Set private key
                                mCryptoService.Key = keyByte;
                               
                                // Encryptor object
                                ICryptoTransform cryptoTransform = mCryptoService.CreateEncryptor();
                       
                                // Memory stream object
                                MemoryStream ms = new MemoryStream();

                                // Crpto stream object
                                CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);

                                // Write encrypted byte to memory stream
                                cs.Write(plainByte, 0, plainByte.Length);
                                cs.FlushFinalBlock();

                                // Get the encrypted byte length
                                byte[] cryptoByte = ms.ToArray();

                                // Convert into base 64 to enable result to be used in Xml
                                return Convert.ToBase64String(cryptoByte, 0, cryptoByte.GetLength(0));
                        }
               
                        public virtual string Decrypt(string cryptoText)
                        {
                                // Convert from base 64 string to bytes
                                byte[] cryptoByte = Convert.FromBase64String(cryptoText);
                                byte[] keyByte = GetLegalKey();

                                // Set private key
                                mCryptoService.Key = keyByte;
                               
                                // Decryptor object
                                ICryptoTransform cryptoTransform = mCryptoService.CreateDecryptor();
                                try
                                {
                                        // Memory stream object
                                        MemoryStream ms = new MemoryStream(cryptoByte, 0, cryptoByte.Length);

                                        // Crpto stream object
                                        CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read);

                                        // Get the result from the Crypto stream
                                        StreamReader sr = new StreamReader(cs);
                                        return sr.ReadToEnd();
                                }
                                catch
                                {
                                        return null;
                                }
                        }

                        #endregion
                }
        }


Andrei
http://www.webxpert.ro

Comments No Comments »

Welcome to my blog one and all.

I’m a software engineer MobiFon S.A. (CONNEX) Romania, a Vodafone owned wireless company . I hope to post here all situations that i meet in my day-to-day activities.
I’m currently MCAD for .NET and studying for MCSD. My transcript is available at: www.microsoft.com/learning/mcp/transcripts . Transcript ID: 679358, access code: andreiash.

Later update:
Starting with 1st of January 2007 I am Technologist at Oracle Corp. Meanwhile, I achived MCSD and OCP.

Thank you.

Andrei
http://www.webxpert.ro

Comments 1 Comment »