436

What is the most modern (best) way of satisfying the following in C#?

string encryptedString = SomeStaticClass.Encrypt(sourceString);

string decryptedString = SomeStaticClass.Decrypt(encryptedString);

BUT with a minimum of fuss involving salts, keys, mucking about with byte[], etc.

Been Googling and confused at what I'm finding (you can see the list of similar SO Qs to see this is a deceptive question to ask).

5
  • 24
    Crypto is not simple. Read blogs.msdn.com/b/ericlippert/archive/2011/09/27/…
    – SLaks
    Apr 16, 2012 at 3:04
  • All crypto operates on byte arrays. Use Encoding.UTF8.
    – SLaks
    Apr 16, 2012 at 3:04
  • 9
    Any answer to this question that just suggests some crypto algorithm and fails to discuss identity, key management, integrity ... is completely worthless.
    – dtb
    Apr 16, 2012 at 3:28
  • 7
    @dtb: I think you're exaggerating the situation here, OP only needs a simple class which might take a chiper, salt, vs. and provides a symmetric encryption. He apparently doesn't care much about the purpose of the functionality.
    – Tarik
    Apr 16, 2012 at 3:45
  • @Tarik No, he isn't exaggerating the situation. Cryptography can be used to secure a system. Without describing the system, applied cryptography is useless (as is the accepted answer). Sep 22, 2014 at 18:56

7 Answers 7

925

UPDATE 23/Dec/2015: Since this answer seems to be getting a lot of upvotes, I've updated it to fix silly bugs and to generally improve the code based upon comments and feedback. See the end of the post for a list of specific improvements.

As other people have said, Cryptography is not simple so it's best to avoid "rolling your own" encryption algorithm.

You can, however, "roll your own" wrapper class around something like the built-in RijndaelManaged cryptography class.

Rijndael is the algorithmic name of the current Advanced Encryption Standard, so you're certainly using an algorithm that could be considered "best practice".

The RijndaelManaged class does indeed normally require you to "muck about" with byte arrays, salts, keys, initialization vectors etc. but this is precisely the kind of detail that can be somewhat abstracted away within your "wrapper" class.

The following class is one I wrote a while ago to perform exactly the kind of thing you're after, a simple single method call to allow some string-based plaintext to be encrypted with a string-based password, with the resulting encrypted string also being represented as a string. Of course, there's an equivalent method to decrypt the encrypted string with the same password.

Unlike the first version of this code, which used the exact same salt and IV values every time, this newer version will generate random salt and IV values each time. Since salt and IV must be the same between the encryption and decryption of a given string, the salt and IV is prepended to the cipher text upon encryption and extracted from it again in order to perform the decryption. The result of this is that encrypting the exact same plaintext with the exact same password gives and entirely different ciphertext result each time.

The "strength" of using this comes from using the RijndaelManaged class to perform the encryption for you, along with using the Rfc2898DeriveBytes function of the System.Security.Cryptography namespace which will generate your encryption key using a standard and secure algorithm (specifically, PBKDF2) based upon the string-based password you supply. (Note this is an improvement of the first version's use of the older PBKDF1 algorithm).

Finally, it's important to note that this is still unauthenticated encryption. Encryption alone provides only privacy (i.e. message is unknown to 3rd parties), whilst authenticated encryption aims to provide both privacy and authenticity (i.e. recipient knows message was sent by the sender).

Without knowing your exact requirements, it's difficult to say whether the code here is sufficiently secure for your needs, however, it has been produced to deliver a good balance between relative simplicity of implementation vs "quality". For example, if your "receiver" of an encrypted string is receiving the string directly from a trusted "sender", then authentication may not even be necessary.

If you require something more complex, and which offers authenticated encryption, check out this post for an implementation.

Here's the code:

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

namespace EncryptStringSample
{
    public static class StringCipher
    {
        // This constant is used to determine the keysize of the encryption algorithm in bits.
        // We divide this by 8 within the code below to get the equivalent number of bytes.
        private const int Keysize = 256;

        // This constant determines the number of iterations for the password bytes generation function.
        private const int DerivationIterations = 1000;

        public static string Encrypt(string plainText, string passPhrase)
        {
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.  
            var saltStringBytes = Generate256BitsOfRandomEntropy();
            var ivStringBytes = Generate256BitsOfRandomEntropy();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return Convert.ToBase64String(cipherTextBytes);
                            }
                        }
                    }
                }
            }
        }

        public static string Decrypt(string cipherText, string passPhrase)
        {
            // Get the complete stream of bytes that represent:
            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode = CipherMode.CBC;
                    symmetricKey.Padding = PaddingMode.PKCS7;
                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream(cipherTextBytes))
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                            using (var streamReader = new StreamReader(cryptoStream, Encoding.UTF8))
                            {
                                return streamReader.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }

        private static byte[] Generate256BitsOfRandomEntropy()
        {
            var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with cryptographically secure random bytes.
                rngCsp.GetBytes(randomBytes);
            }
            return randomBytes;
        }
    }
}

The above class can be used quite simply with code similar to the following:

using System;

namespace EncryptStringSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a password to use:");
            string password = Console.ReadLine();
            Console.WriteLine("Please enter a string to encrypt:");
            string plaintext = Console.ReadLine();
            Console.WriteLine("");

            Console.WriteLine("Your encrypted string is:");
            string encryptedstring = StringCipher.Encrypt(plaintext, password);
            Console.WriteLine(encryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Your decrypted string is:");
            string decryptedstring = StringCipher.Decrypt(encryptedstring, password);
            Console.WriteLine(decryptedstring);
            Console.WriteLine("");

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    }
}

(You can download a simple VS2013 sample solution (which includes a few unit tests) here).

UPDATE 23/Dec/2015: The list of specific improvements to the code are:

  • Fixed a silly bug where encoding was different between encrypting and decrypting. As the mechanism by which salt & IV values are generated has changed, encoding is no longer necessary.
  • Due to the salt/IV change, the previous code comment that incorrectly indicated that UTF8 encoding a 16 character string produces 32 bytes is no longer applicable (as encoding is no longer necessary).
  • Usage of the superseded PBKDF1 algorithm has been replaced with usage of the more modern PBKDF2 algorithm.
  • The password derivation is now properly salted whereas previously it wasn't salted at all (another silly bug squished).
55
  • 11
    code review: PBKDF2 makes more senses since you are generating more than 160 bits of key material. However ur PBKDF1 isn't even salted contrary to statement above. Your comments about IV are incorrect, a 16 character UTF8 is 16 bytes, it works anyway because IV size is actually based on block size, not key size. Also IV is being ascii decoded instead of utf8 decoded in decrypt. Ur answer talks about abstracting away salts and IVs but really u just removed them -- not modern or secure
    – jbtule
    Oct 18, 2013 at 21:25
  • 7
    @CraigTP Good explanation but 1000 iterations is very low. When the PBKDF2 standard was written in 2000, the recommended minimum number of iterations was 1000, but the parameter is intended to be increased over time as CPU speeds increase. As of 2005 a Kerberos standard recommended 4096 iterations, Apple iOS 3 used 2000, iOS 4 used 10000, while in 2011 LastPass used 5000 iterations for JavaScript clients and 100000 iterations for server-side hashing.
    – Ogglas
    Jun 10, 2016 at 10:34
  • 14
    Any chance for a .net Core update, since RijndaelManaged() class is not avaliable in Core? Aug 1, 2016 at 13:22
  • 23
    I am not allowed to answer the question, so I just comment here. As far as .NET Standard 2 goes, the block size must be 128. Here's how it changes your code: github.com/nopara73/DotNetEssentials/blob/master/…
    – nopara73
    Jan 14, 2018 at 7:07
  • 6
    This not longer seems to work in .NET 6, the decrypted data is truncated.
    – Thurfir
    Jul 28, 2022 at 9:45
139
using System.IO;
using System.Text;
using System.Security.Cryptography;

public static class EncryptionHelper
{
    public static string Encrypt(string clearText)
    {
        string EncryptionKey = "abc123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }
        return clearText;
    }
    public static string Decrypt(string cipherText)
    {
        string EncryptionKey = "abc123";
        cipherText = cipherText.Replace(" ", "+");
        byte[] cipherBytes = Convert.FromBase64String(cipherText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                cipherText = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return cipherText;
    }
}
16
  • 5
    You probably shouldn't hard code the encryption key into the methods. Jan 14, 2015 at 14:30
  • 13
    This is very useful and simple for the numerous cases where we do not need the complexities of salt. I just made the encryption key a parameter and was able to use the code successfully as is. Jan 22, 2016 at 9:30
  • 6
    @FrenkyB to make the method portable, you can always pass the key as a method parameter. For example: public static string Encrypt(string clearText, string encryptionKey) This way you can have unique keys for each method call.
    – sojim2
    Nov 30, 2016 at 17:31
  • 8
    My Code Analyzer warned that variable cs is being disposed twice. We do not need redundant statements cs.Close() in both Encrypt and Decrypt methods, since both will be disposed once control exists the using block. Jul 8, 2017 at 9:49
  • 14
    Why do you replace spaces with +?
    – Simon
    Jul 31, 2019 at 15:43
45

If you are targeting ASP.NET Core that does not support RijndaelManaged yet, you can use IDataProtectionProvider.

First, configure your application to use data protection:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDataProtection();
    }
    // ...
}

Then you'll be able to inject IDataProtectionProvider instance and use it to encrypt/decrypt data:

public class MyService : IService
{
    private const string Purpose = "my protection purpose";
    private readonly IDataProtectionProvider _provider;

    public MyService(IDataProtectionProvider provider)
    {
        _provider = provider;
    }

    public string Encrypt(string plainText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Protect(plainText);
    }

    public string Decrypt(string cipherText)
    {
        var protector = _provider.CreateProtector(Purpose);
        return protector.Unprotect(cipherText);
    }
}

See this article for more details.

4
  • 2
    best one for me, I'm using asp.netcore 3.1, thanks.
    – SexyBoooom
    Jun 2, 2020 at 20:03
  • 17
    A quick note about the article you provided is that it states: "Encryption requires a key, which is created and managed by the data protection system. Keys are created with a default lifetime of 90 days, and stored in a suitable location according to the environment. Keys are temporary, so the data protection API is designed mainly for short term data protection scenarios". Just beware if you implement this method, that your keys expire after 90 days per default. Jul 15, 2020 at 12:32
  • 1
    This should now be the accepted answer since the author mentions/is asking for the " most modern (best) way" and "with a minimum of fuss involving salts, key" implementation.
    – sharpc
    Mar 25, 2022 at 12:13
  • Just wanted to mention that services.AddDataProtection() has to stand alone or has to be the last services.Add...() method if you concat them as it doesn't return an IServiceCollection.
    – IngoB
    May 5, 2022 at 11:02
31

Try this class:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            var cs = new CryptoStream(ms,
                symm.CreateEncryptor(symm.Key, symm.IV),
                CryptoStreamMode.Write);

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = ms.ToArray();

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}

and use it like this:

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);
8
  • 3
    This is not a bad answer because diversity is what may keep encryption algorithms strong. I don't think a warning on this particular approach robustness is needed since no encryption mechanism is perfect, after all.
    – Bigger
    Oct 30, 2013 at 6:50
  • 1
    This answer is decent. TDES is used a lot to secure ATM transactions as they travel over the phone line. I +1'd it, I'm not sure why someone else had -1'd it.
    – psyklopz
    Dec 4, 2013 at 18:46
  • 3
    Diversity is not what keeps encryption algorithms strong. Math does that :) DES (even triple DES) is an old algorithm that is no longer strong enough for most applications.
    – Eric W
    Jul 2, 2014 at 16:57
  • 1
    This was exactly what i was looking for my application. Dont need much just a way to make sure a user cant choose the next integer in sequence. So instead of using a link that has 380 plugged in they get some random string so they can't use 381 instead. Sep 27, 2014 at 17:28
  • 1
    3DES isn't optimal, but it isn't the biggest problem with this answer. Your don't have a MAC, enabling active attacks like padding oracles. Leaving the IV management to the caller is a bad idea as well, since they will almost certainly mess it up, typically by using a fixed IV instead of generating a different one for each message. Feb 19, 2015 at 21:46
21

If you need to store a password in memory and would like to have it encrypted you should use SecureString:

http://msdn.microsoft.com/en-us/library/system.security.securestring.aspx

For more general uses I would use a FIPS approved algorithm such as Advanced Encryption Standard, formerly known as Rijndael. See this page for an implementation example:

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx

4
  • SecureString doesnt seem to be a good fit I think but it is a good thing when you are working within a secure environment like apps for banks...
    – Tarik
    Apr 16, 2012 at 3:24
  • It really depends on what you need to do. I was first introduced to it when we were required to encrypt in-memory credentials in applications for the government.
    – Ulises
    Apr 16, 2012 at 4:24
  • They also provide AES (and others), besides Rijndael: learn.microsoft.com/en-us/dotnet/api/…
    – Ioanna
    Aug 29, 2018 at 8:53
  • 1
    SecureString is deprecated MS recommends not using it github.com/dotnet/platform-compat/blob/master/docs/DE0001.md
    – Menahem
    Mar 4, 2021 at 14:50
13

You may be looking for the ProtectedData class, which encrypts data using the user's logon credentials.

6
  • 4
    I read MSDN documentation but it doesnt state that what would happen if we moved these encrypted data to some another machine with different credentials. So we would still be able decrypt it back?
    – Tarik
    Apr 16, 2012 at 3:18
  • 1
    @Braveyard Just decrypt it when exporting and encrypt it again on the new machine. Apr 16, 2012 at 3:39
  • 2
    @RichardHein: I thought that too, but doesn't seem a wise advice. When I move the info, I don't like to do that in plain human readable format, otherwise what's the meaning of all these encryption things..
    – Tarik
    Apr 16, 2012 at 3:43
  • @Braveyard Then decrypt on old machine - encrypt again using a shared key for transport, on old machine - decrypt on new machine with shared key - encrypt with new machine key? Apr 16, 2012 at 11:39
  • 1
    @RichardHein: If you want to move data across machines, ProtectedData is the wrong tool for the job. (Unless you're in a domain, so that they'd have the same users everywhere)
    – SLaks
    Apr 16, 2012 at 13:09
-2

The easiest way that I've seen to do encryption is through RSA

Check out the MSDN on it: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx

It does involve using bytes, but when it comes down to it you kind of do want encryption and decryption to be tough to figure out otherwise it will be easy to hack.

1
  • 9
    RSA is asymmetric, which is unlikely to be what he wants.
    – SLaks
    Apr 16, 2012 at 3:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.