Compress & Decompress String in C#

Compress and decompress string in C#.

Usage

var str = "String to be compressed";
var strCompressed = Cipher.Compress(str);
var strDecompressed = Cipher.Decompress(strCompressed);

Cipher class

using System;
using System.IO;
using System.IO.Compression;
using System.Text;

public static class Cipher
{
    /// <summary>
    /// String compress
    /// </summary>
    public static string Compress(string uncompressedString)
    {
        if (String.IsNullOrEmpty(uncompressedString))
        {
            return uncompressedString;
        }

        using (var compressedStream = new MemoryStream())
        {
            using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
            {
                using (var compressorStream = new DeflateStream(compressedStream, CompressionMode.Compress, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                return Convert.ToBase64String(compressedStream.ToArray());
            }
        }
    }

    /// <summary>
    /// String decompress
    /// </summary>
    public static string Decompress(string compressedString)
    {
        if (String.IsNullOrEmpty(compressedString))
        {
            return compressedString;
        }

        using (var decompressedStream = new MemoryStream())
        {
            using (var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString)))
            {
                using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
                {
                    decompressorStream.CopyTo(decompressedStream);
                }

                return Encoding.UTF8.GetString(decompressedStream.ToArray());
            }
        }
    }
}
Etiketler:  C#

Generic Singleton Pattern & C#

Generic Singleton pattern with C# and .NET 4 (or higher)

// T is a class and must have a public default constructor.

public sealed class Singleton<T> where T : class, new()
{
    private static readonly Lazy<T> instance = new Lazy<T>(() => new T());
        
    public static T Instance
    {
        get
        {
            return instance.Value;
        }
    }

    private Singleton() { }
}

Usage:

var myClass = Singleton<MyClass>.Instance;
Etiketler:  C#

Encrypt & Decrypt a String in C#

Encrypt and decrypt data using a symmetric key in C#.

Usage

var str = "String to be encrypted";
var password = "p@SSword";
var strEncryptred = Cipher.Encrypt(str, password);
var strDecrypted = Cipher.Decrypt(strEncryptred, password);

Encryption

Cipher class

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

namespace SG.Algoritma
{
    public static class Cipher
    {
        /// <summary>
        /// Encrypt a string.
        /// </summary>
        /// <param name="plainText">String to be encrypted</param>
        /// <param name="password">Password</param>
        public static string Encrypt(string plainText, string password)
        {
            if (plainText == null)
            {
                return null;
            }

            if (password == null)
            {
                password = String.Empty;
            }

            // Get the bytes of the string
            var bytesToBeEncrypted = Encoding.UTF8.GetBytes(plainText);
            var passwordBytes = Encoding.UTF8.GetBytes(password);

            // Hash the password with SHA256
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

            var bytesEncrypted = Cipher.Encrypt(bytesToBeEncrypted, passwordBytes);

            return Convert.ToBase64String(bytesEncrypted);
        }

        /// <summary>
        /// Decrypt a string.
        /// </summary>
        /// <param name="encryptedText">String to be decrypted</param>
        /// <param name="password">Password used during encryption</param>
        /// <exception cref="FormatException"></exception>
        public static string Decrypt(string encryptedText, string password)
        {
            if (encryptedText == null)
            {
                return null;
            }

            if (password == null)
            {
                password = String.Empty;
            }

            // Get the bytes of the string
            var bytesToBeDecrypted = Convert.FromBase64String(encryptedText);
            var passwordBytes = Encoding.UTF8.GetBytes(password);

            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);

            var bytesDecrypted = Cipher.Decrypt(bytesToBeDecrypted, passwordBytes);

            return Encoding.UTF8.GetString(bytesDecrypted);
        }

        private static byte[] Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
        {
            byte[] encryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);

                    AES.KeySize = 256;
                    AES.BlockSize = 128;
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);

                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
                        cs.Close();
                    }

                    encryptedBytes = ms.ToArray();
                }
            }

            return encryptedBytes;
        }

        private static byte[] Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
        {
            byte[] decryptedBytes = null;

            // Set your salt here, change it to meet your flavor:
            // The salt bytes must be at least 8 bytes.
            var saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged AES = new RijndaelManaged())
                {
                    var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);

                    AES.KeySize = 256;
                    AES.BlockSize = 128;
                    AES.Key = key.GetBytes(AES.KeySize / 8);
                    AES.IV = key.GetBytes(AES.BlockSize / 8);
                    AES.Mode = CipherMode.CBC;

                    using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
                        cs.Close();
                    }

                    decryptedBytes = ms.ToArray();
                }
            }

            return decryptedBytes;
        }
    }
}
Etiketler:  C#

Kategoriler

Algoritma (5), Cheat Sheet (2), Framework (3), İpucu (5), Kendime Not (1), Kitap (4), Kod (5), Matematik (1), Proje (5), Veritabanı (3), Workshop (3)

Etiketler

C# (13) HTML (1) JavaScript (2) SQL (3)

İngilizce / Türkçe

İngilizce / Türkçe kelime listesi kendime not