Skip to main content

Encrypts the data in a specified byte array and returns a byte array that contains the encrypted data.

using System;
using System.Text;
using System.Security.Cryptography;
using System.Diagnostics;

namespace Extensions
{
    public static class StringExtensions
    {
        public static string Encrypt(this string clearText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.LocalMachine)
        {
            if (string.IsNullOrEmpty(clearText))
            {
                throw new ArgumentNullException(nameof(clearText));
            }

            byte[] clearBytes = Encoding.UTF8.GetBytes(clearText);
            byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy) ? null : Encoding.UTF8.GetBytes(optionalEntropy);

            try
            {
                byte[] encryptedBytes = ProtectedData.Protect(clearBytes, entropyBytes, scope);
                return "encrypted-" + Convert.ToBase64String(encryptedBytes);
            }
            catch (CryptographicException ex)
            {
                Debug.WriteLine("Data was not encrypted. An error occurred.");
                Debug.WriteLine(ex.Message);
            }

            return null;
        }

        public static string Decrypt(this string encryptedText, string optionalEntropy = null, DataProtectionScope scope = DataProtectionScope.LocalMachine)
        {
            if (string.IsNullOrEmpty(encryptedText))
            {
                throw new ArgumentNullException(nameof(encryptedText));
            }

            // remove encrypted- tag from beginning
            encryptedText = encryptedText.Remove(0, 10);

            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            byte[] entropyBytes = string.IsNullOrEmpty(optionalEntropy) ? null : Encoding.UTF8.GetBytes(optionalEntropy);

            try
            {
                byte[] clearBytes = ProtectedData.Unprotect(encryptedBytes, entropyBytes, scope);
                if (clearBytes != null)
                {
                    return Encoding.UTF8.GetString(clearBytes);
                }
            }
            catch (CryptographicException ex)
            {
                Debug.WriteLine("Data was not decrypted. An error occurred.");
                Debug.WriteLine(ex.Message);
            }

            return null;
        }
    }
}