# VBForums CodeBank > CodeBank - C# >  Encrypt / Unencrypt string (for password etc)

## Merrion

```
    public class EncryptUtility
    {

        // Encryption/Decryption
        private static System.Security.Cryptography.TripleDESCryptoServiceProvider tdes = null;
        private static System.Security.Cryptography.ICryptoTransform _encryptor;
        private static System.Security.Cryptography.ICryptoTransform _decryptor;

        private static byte[] _key = new byte[] { 162, 35, 204, 42, 81, 158, 34, 101, 115, 86, 201, 94, 113, 42, 7, 74, 35, 166, 225, 202, 216, 159, 127, 93 };
        private static byte[] _iv = new byte[] { 176, 158, 98, 232, 230, 189, 210, 90 };


        #region Encryption/decription code
        /// <summary>
        /// Encrypts a password using the given key
        /// </summary>
        /// <param name="clearPassword">
        /// The password to encrypt
        /// </param>
        /// <param name="key">
        /// The key phrase as an ascii string
        /// </param>
        /// <returns>
        /// An encrypted version of the password 
        /// </returns>
        public static string EncryptPassword(string clearPassword, string key)
        {
            // Convert the passphrase to a set of bytes that fits the requirement
            byte[] _putativeKey = Convert.FromBase64String(Convert.ToBase64String(System.Text.UnicodeEncoding.Unicode.GetBytes(key)  ));
            byte[] _newKey = new byte[_key.Length];



            for (int i = 0; i < _newKey.Length  ; i++)
            {
                if (i < _putativeKey.Length)
                {
                    _newKey[i] = _putativeKey[i];
                }
                else
                {
                    _newKey[i] = _key[i];
                }
            }

            return EncryptPassword(clearPassword, _newKey);

        }

        /// <summary>
        /// Encrypts the given clear text password with the given key
        /// </summary>
        /// <param name="clearPassword">
        /// The password to encrypt
        /// </param>
        /// <param name="key">
        /// The key to use to encrypt the password
        /// </param>
        /// <returns>
        /// An encrypted ascii string to store the password
        /// </returns>
        public static string EncryptPassword(string clearPassword, byte[] key)
        {

            EncryptUtility.EncryptionKey = key;

            if (null != _encryptor)
            {
                System.IO.MemoryStream msTarget = new System.IO.MemoryStream(1024);

                System.Security.Cryptography.CryptoStream csTarget = new System.Security.Cryptography.CryptoStream(msTarget  , _encryptor, System.Security.Cryptography.CryptoStreamMode.Write);
                byte[] _clearPassword = System.Text.UnicodeEncoding.Unicode.GetBytes(clearPassword );
                csTarget.Write(_clearPassword  , 0 , _clearPassword.Length );
                csTarget.FlushFinalBlock(); 

                // The in-memory stream now holds the encrypted password
                msTarget.Seek(0, System.IO.SeekOrigin.Begin);

                byte[] encrypted = msTarget.ToArray();
                return Convert.ToBase64String(encrypted);

            }
            else
            {
                throw new ApplicationException(@"Invalid encryption key - cannot encrypt password");
            }


        }


        /// <summary>
        /// Encrypts the given clear text password with the default key
        /// </summary>
        /// <param name="clearPassword">
        /// The password to encrypt
        /// </param>
        /// <param name="key">
        /// The key to use to encrypt the password
        /// </param>
        /// <returns>
        /// An encrypted ascii string to store the password
        /// </returns>
        public static string EncryptPassword(string clearPassword)
        {
            return EncryptPassword(clearPassword, EncryptUtility._key); 
        }

        /// <summary>
        /// Decrypts a password using the given pass phrase
        /// </summary>
        /// <param name="encryptedPassword">
        /// The encrypted password to decrypt
        /// </param>
        /// <param name="key">
        /// The passphrase to use to generate the encryption key
        /// </param>
        /// <returns></returns>
        public static string DecryptPassword(string encryptedPassword, string key)
        {
            // Convert the passphrase to a set of bytes that fits the requirement
            byte[] _putativeKey = Convert.FromBase64String(Convert.ToBase64String(System.Text.UnicodeEncoding.Unicode.GetBytes(key)));
            byte[] _newKey = new byte[_key.Length];



            for (int i = 0; i < _newKey.Length; i++)
            {
                if (i < _putativeKey.Length)
                {
                    _newKey[i] = _putativeKey[i];
                }
                else
                {
                    _newKey[i] = _key[i];
                }
            }

            return DecryptPassword(encryptedPassword, _newKey);
        }

        /// <summary>
        /// Un-encrypt the given encrypted password using the given key
        /// </summary>
        /// <param name="encryptedPassword">
        /// The encrypted password to un-encrypt
        /// </param>
        /// <param name="key">
        /// The key used in the encryption
        /// </param>
        /// <returns></returns>
        public static string DecryptPassword(string encryptedPassword, byte[] key)
        {
            EncryptUtility.EncryptionKey = key;

            if (null != _decryptor)
            {
                System.IO.MemoryStream msTarget = new System.IO.MemoryStream(1024);

                // Put the encrypted password in the memory stream..
                byte[] _encyptedPassword = Convert.FromBase64String(encryptedPassword);
                msTarget.Write(_encyptedPassword, 0, _encyptedPassword.Length );

                // Create a decryption reader
                System.Security.Cryptography.CryptoStream csTarget = new System.Security.Cryptography.CryptoStream(msTarget, _decryptor , System.Security.Cryptography.CryptoStreamMode.Read);

                msTarget.Seek(0, System.IO.SeekOrigin.Begin); 
                System.IO.StreamReader srOut = new System.IO.StreamReader(csTarget , System.Text.UnicodeEncoding.Unicode);
                //csTarget.FlushFinalBlock();

                // Return what we have written to the stream
                return srOut.ReadToEnd();
            }
            else
            {
                throw new ApplicationException(@"Invalid encryption key - cannot decrypt password");
            }

        }

        /// <summary>
        /// Un encrypt the given encrypted password using the default key
        /// </summary>
        /// <param name="encryptedPassword">
        /// The encrypted password to un-encrypt
        /// </param>
        /// <returns></returns>
        public static string DecryptPassword(string encryptedPassword)
        {
            return DecryptPassword(encryptedPassword, EncryptUtility._key);
        }

        /// <summary>
        /// Sets the array of bytes to use as the encryption key for encrypting
        /// or decrypting the file transfer passwords 
        /// </summary>
        public static byte[] EncryptionKey
        {
            set {
                if ((null != value) && (value.Length > 0))
                {
                    FileTransferDefinition._key = value;
                    if (null == tdes)
                    {
                        tdes = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
                        tdes.IV = _iv;
                    }

                    // Set the new key
                    tdes.Key = EncryptUtility._key;

                    // and recreate the encryptor and decryptor
                    _encryptor = tdes.CreateEncryptor();
                    _decryptor = tdes.CreateDecryptor();

                }
            }
        }

        #endregion

    }
```

----------


## HongKongCV

Okay, I am needing to encrypt data so I downloaded this and gave it a try.  I am getting a compile error.  You haven't defined FileTransferDefinition or given a NameSpace where it can be found.  Every reference to FileTransferDefinition kicks out an error:

"The name 'FileTransferDefinition' does not exist in the current context"

What's missing?

----------


## Merrion

Oops - I renamed the class to "EncryptUtility" (it was cut from a much much larger project) but forgot to rename the local references  :Blush: 

Should be OK now.

----------

