views:

24006

answers:

9

Can someone give me the code to Encrypt and Decrypt a string in C#? I'm trying to do this with TripleDES but that is not a requirement.

A: 

Mono already supports the same classes that Microsoft .NET does when it comes to encryption. So you can use DES, AES, RSA, or whatever you want.

amdfan
+20  A: 

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));

For more info, visit MSDN - RSACryptoServiceProvider

DrJokepu
Sorry to ask such a simple question but can anyone tell me where do I get RSA Key or how do i generate one?
Akash Kava
Akash Kava: Why don't you ask it on stackoverflow.com's sister site, http://superuser.com/ ?
DrJokepu
+1  A: 

Take a look at the System.Security.Cryptography namespace. Those classes should work in both the Microsoft and Mono implementations.

What kind of encryption are you trying to do?

amcoder
+6  A: 

Here is a working example:

http://www.codeproject.com/KB/security/DotNetCrypto.aspx

NotDan
+13  A: 

Every other answer pretty much covered using the .net cryptography classes. Whatever you do, please don't try to make up your own encryption technique. This never ends well. Unless you are a world-class mathematician with a team of other mathematicians, you have no reason for trying to improve that wheel.

IAmCodeMonkey
A: 

This is an area that is really lacking in .NET. I was expecting to see something like this...

string encryptedString = EncrypterClass.Encrypt(key, content);

Instead of abstracting simple encryption out in a library, MS forces you to jump though all kinds of silly hoops (bytes, streams, and string oh my!!) I think my encryption code is at least 20 lines of code :(. I hope they improve this in the future.

The libraries in .NET are powerful and flexible, but they sacrifice simplicity to get that power and flexibility. So in your own code, you have to come up with certain conventions and then build your own simple abstractions over the .NET library complexity.
Justice
+7  A: 

Here's a working example derived from the "RijndaelManaged Class" documentation. Good luck!

public class Crypto
{
    private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

    /// <summary>
    /// Encrypt the given string using AES.  The string can be decrypted using 
    /// DecryptStringAES().  The sharedSecret parameters must match.
    /// </summary>
    /// <param name="plainText">The text to encrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for encryption.</param>
    public static string EncryptStringAES(string plainText, string sharedSecret)
    {
        if(string.IsNullOrEmpty(plainText))
            throw new ArgumentNullException("plainText");
        if(string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        string outStr = null;                       // Encrypted string to return
        RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = new RijndaelManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
            aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                }
                outStr = Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        // Return the encrypted bytes from the memory stream.
        return outStr;
    }

    /// <summary>
    /// Decrypt the given string.  Assumes the string was encrypted using 
    /// EncryptStringAES(), using an identical sharedSecret.
    /// </summary>
    /// <param name="cipherText">The text to decrypt.</param>
    /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
    public static string DecryptStringAES(string cipherText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(cipherText))
            throw new ArgumentNullException("cipherText");
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // Declare the RijndaelManaged object
        // used to decrypt the data.
        RijndaelManaged aesAlg = null;

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        try
        {
            // generate the key from the shared secret and the salt
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

            // Create a RijndaelManaged object
            // with the specified key and IV.
            aesAlg = new RijndaelManaged();
            aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
            aesAlg.IV = key.GetBytes(aesAlg.BlockSize / 8);

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            // Create the streams used for decryption.                
            byte[] bytes = Convert.FromBase64String(cipherText);
            using (MemoryStream msDecrypt = new MemoryStream(bytes))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                }
            }
        }
        finally
        {
            // Clear the RijndaelManaged object.
            if (aesAlg != null)
                aesAlg.Clear();
        }

        return plaintext;
    }
}
Brett
A: 

I have used this method in the past

C# encryption

Josh.R.Harrison
A: 

lovely. Thanks so much for the working code. I spent almost a day on how to decrypt and encrypted value and was almost given up. But this code seems to be working for me.

preeti