Link to home
Start Free TrialLog in
Avatar of pdering
pdering

asked on

How to encrypt string in c#?

I want to store a value in the registry but I want it to be encrypted.  How do I do this?  I also need to be able to decrypt it.  I'm using C#.
Avatar of Rikin Shah
Rikin Shah
Flag of India image

Hi Pdering,

A simple example would be better to make encryption-decryption understand:
http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C

Regards,
Rikin.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Member_2_99151
Member_2_99151

Hi,

I always use the code here to do any simple text encryption...

http://www.dijksterhuis.org/encrypting-decrypting-string/

James
Here is an example using RSA. Replace your_rsa_key with your RSA key.

var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
provider.ImportParameters(your_rsa_key);

var encryptedBytes = provider.Encrypt(
    System.Text.Encoding.UTF8.GetBytes("Hello World!"), true);

string decryptedTest = System.Text.Encoding.UTF8.GetString(
    provider.Decrypt(encryptedBytes, true));

Open in new window


For more info, visit MSDN - RSACryptoServiceProvider
also you can leverage on System.Security.Cryptography Namespace

 http://msdn.microsoft.com/en-us/library/system.security.cryptography.aspx
I use these 2 extension methods:

    public static class ExtensionMethods_String
    {
        /// <summary>
        /// Encrypts a string using the supplied key. Encoding is done using RSA encryption.
        /// </summary>
        /// <param name="stringToEncrypt">String that must be encrypted.</param>
        /// <param name="key">Encryptionkey.</param>
        /// <param name="encoding">Text Encoding</param>
        /// <returns>A string representing a Byte array separated by a minus sign.</returns>
        /// <exception cref="ArgumentException">Occurs when stringToEncrypt or key is null or empty.</exception>
        public static String Encrypt(this String stringToEncrypt, String key, Encoding encoding)
        {
            if (String.IsNullOrEmpty(stringToEncrypt))
                throw new ArgumentException("An empty string value cannot be encrypted.");

            if (String.IsNullOrEmpty(key))
                throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");

            CspParameters cspp = new CspParameters();
            cspp.KeyContainerName = key;

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
            rsa.PersistKeyInCsp = true;

            Byte[] Bytes = rsa.Encrypt(encoding.GetBytes(stringToEncrypt), true);

            return BitConverter.ToString(Bytes);
        }

        /// <summary>
        /// Decrypts a string using the supplied key. Decoding is done using RSA encryption.
        /// </summary>
        /// <param name="stringToDecrypt">String that must be decrypted.</param>
        /// <param name="key">Decryptionkey.</param>
        /// <param name="encoding">Text Encoding</param>
        /// <returns>The decrypted string or null if decryption failed.</returns>
        /// <exception cref="ArgumentException">Occurs when stringToDecrypt or key is null or empty.</exception>
        public static String Decrypt(this String stringToDecrypt, String key, Encoding encoding)
        {
            String result = null;

            if (String.IsNullOrEmpty(stringToDecrypt))
                throw new ArgumentException("An empty string value cannot be encrypted.");

            if (String.IsNullOrEmpty(key))
                throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");

            try
            {
                CspParameters cspp = new CspParameters();
                cspp.KeyContainerName = key;

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
                rsa.PersistKeyInCsp = true;

                String[] decryptArray = stringToDecrypt.Split(new String[] { "-" }, StringSplitOptions.None);
                Byte[] decryptByteArray = Array.ConvertAll<String, Byte>(decryptArray, (s => Convert.ToByte(Byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


                Byte[] Bytes = rsa.Decrypt(decryptByteArray, true);

                result = encoding.GetString(Bytes);
            }
            finally
            {
                // no need for further processing
            }

            return result;
        }
   }

Open in new window


The usage is as simple as:
String EncryptedString = MyString.Encrypt(MyKey, Encoding.UTF8);
String DecryptedString = EncryptedString.Decrypt(MyKey, Encoding.UTF8)

Open in new window


Hope this helps.
Regards.