Meliodas0_0

Text ecrypt

Feb 4th, 2020
226
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Text;
  3. using System.Security.Cryptography;
  4. using System.IO;
  5. using System.Linq;
  6.  
  7. namespace EncryptStringSample
  8. {
  9.    public static class StringCipher
  10.    {
  11.        // This constant is used to determine the keysize of the encryption algorithm in bits.
  12.        // We divide this by 8 within the code below to get the equivalent number of bytes.
  13.        private const int Keysize = 256;
  14.  
  15.        // This constant determines the number of iterations for the password bytes generation function.
  16.        private const int DerivationIterations = 1000;
  17.  
  18.        public static string Encrypt(string plainText, string passPhrase)
  19.        {
  20.            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
  21.            // so that the same Salt and IV values can be used when decrypting.  
  22.            var saltStringBytes = Generate256BitsOfRandomEntropy();
  23.            var ivStringBytes = Generate256BitsOfRandomEntropy();
  24.            var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
  25.            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
  26.            {
  27.                var keyBytes = password.GetBytes(Keysize / 8);
  28.                using (var symmetricKey = new RijndaelManaged())
  29.                {
  30.                    symmetricKey.BlockSize = 256;
  31.                    symmetricKey.Mode = CipherMode.CBC;
  32.                    symmetricKey.Padding = PaddingMode.PKCS7;
  33.                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
  34.                    {
  35.                        using (var memoryStream = new MemoryStream())
  36.                        {
  37.                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
  38.                            {
  39.                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  40.                                cryptoStream.FlushFinalBlock();
  41.                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
  42.                                var cipherTextBytes = saltStringBytes;
  43.                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
  44.                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
  45.                                memoryStream.Close();
  46.                                cryptoStream.Close();
  47.                                return Convert.ToBase64String(cipherTextBytes);
  48.                            }
  49.                        }
  50.                    }
  51.                }
  52.            }
  53.        }
  54.  
  55.        public static string Decrypt(string cipherText, string passPhrase)
  56.        {
  57.            // Get the complete stream of bytes that represent:
  58.            // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
  59.            var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
  60.            // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
  61.            var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
  62.            // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
  63.            var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
  64.            // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
  65.            var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
  66.  
  67.            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
  68.            {
  69.                var keyBytes = password.GetBytes(Keysize / 8);
  70.                using (var symmetricKey = new RijndaelManaged())
  71.                {
  72.                    symmetricKey.BlockSize = 256;
  73.                    symmetricKey.Mode = CipherMode.CBC;
  74.                    symmetricKey.Padding = PaddingMode.PKCS7;
  75.                    using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
  76.                    {
  77.                        using (var memoryStream = new MemoryStream(cipherTextBytes))
  78.                        {
  79.                            using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
  80.                            {
  81.                                var plainTextBytes = new byte[cipherTextBytes.Length];
  82.                                var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
  83.                                memoryStream.Close();
  84.                                cryptoStream.Close();
  85.                                return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
  86.                            }
  87.                        }
  88.                    }
  89.                }
  90.            }
  91.        }
  92.  
  93.        private static byte[] Generate256BitsOfRandomEntropy()
  94.        {
  95.            var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
  96.            using (var rngCsp = new RNGCryptoServiceProvider())
  97.            {
  98.                // Fill the array with cryptographically secure random bytes.
  99.                rngCsp.GetBytes(randomBytes);
  100.            }
  101.            return randomBytes;
  102.        }
  103.    }
  104. }
RAW Paste Data