Advertisement
hubert17

Encryption in ASP.NET C#

Jan 19th, 2018
417
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.05 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.Security.Cryptography;
  4. using System.IO;
  5. using System.Linq;
  6.  
  7. namespace Gabs.Helpers
  8. {
  9.     public static class EncryptionRijndael
  10.     {
  11.         private const string EncryptionKey = "gabs123";
  12.  
  13.         // This constant is used to determine the keysize of the encryption algorithm in bits.
  14.         // We divide this by 8 within the code below to get the equivalent number of bytes.
  15.         private const int Keysize = 256;
  16.  
  17.         // This constant determines the number of iterations for the password bytes generation function.
  18.         private const int DerivationIterations = 1000;
  19.  
  20.         public static string Encrypt(string clearText, string passPhrase = EncryptionKey)
  21.         {
  22.             // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
  23.             // so that the same Salt and IV values can be used when decrypting.  
  24.             var saltStringBytes = Generate256BitsOfRandomEntropy();
  25.             var ivStringBytes = Generate256BitsOfRandomEntropy();
  26.             var plainTextBytes = Encoding.UTF8.GetBytes(clearText);
  27.             using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
  28.             {
  29.                 var keyBytes = password.GetBytes(Keysize / 8);
  30.                 using (var symmetricKey = new RijndaelManaged())
  31.                 {
  32.                     symmetricKey.BlockSize = 256;
  33.                     symmetricKey.Mode = CipherMode.CBC;
  34.                     symmetricKey.Padding = PaddingMode.PKCS7;
  35.                     using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
  36.                     {
  37.                         using (var memoryStream = new MemoryStream())
  38.                         {
  39.                             using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
  40.                             {
  41.                                 cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
  42.                                 cryptoStream.FlushFinalBlock();
  43.                                 // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
  44.                                 var cipherTextBytes = saltStringBytes;
  45.                                 cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
  46.                                 cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
  47.                                 memoryStream.Close();
  48.                                 cryptoStream.Close();
  49.                                 return Convert.ToBase64String(cipherTextBytes);
  50.                             }
  51.                         }
  52.                     }
  53.                 }
  54.             }
  55.         }
  56.  
  57.         public static string Decrypt(string cipherText, string passPhrase = EncryptionKey)
  58.         {
  59.             // Get the complete stream of bytes that represent:
  60.             // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
  61.             var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
  62.             // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
  63.             var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
  64.             // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
  65.             var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
  66.             // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
  67.             var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
  68.  
  69.             using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
  70.             {
  71.                 var keyBytes = password.GetBytes(Keysize / 8);
  72.                 using (var symmetricKey = new RijndaelManaged())
  73.                 {
  74.                     symmetricKey.BlockSize = 256;
  75.                     symmetricKey.Mode = CipherMode.CBC;
  76.                     symmetricKey.Padding = PaddingMode.PKCS7;
  77.                     using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
  78.                     {
  79.                         using (var memoryStream = new MemoryStream(cipherTextBytes))
  80.                         {
  81.                             using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
  82.                             {
  83.                                 var plainTextBytes = new byte[cipherTextBytes.Length];
  84.                                 var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
  85.                                 memoryStream.Close();
  86.                                 cryptoStream.Close();
  87.                                 return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
  88.                             }
  89.                         }
  90.                     }
  91.                 }
  92.             }
  93.         }
  94.  
  95.         private static byte[] Generate256BitsOfRandomEntropy()
  96.         {
  97.             var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
  98.             using (var rngCsp = new RNGCryptoServiceProvider())
  99.             {
  100.                 // Fill the array with cryptographically secure random bytes.
  101.                 rngCsp.GetBytes(randomBytes);
  102.             }
  103.             return randomBytes;
  104.         }
  105.     }
  106.  
  107.     public static class EncryptionAES
  108.     {
  109.         private const string EncryptionKey = "gabs123";
  110.  
  111.         public static string Encrypt(string clearText, string passPhrase = EncryptionKey)
  112.         {
  113.             byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
  114.             using (Aes encryptor = Aes.Create())
  115.             {
  116.                 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(passPhrase, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
  117.                 encryptor.Key = pdb.GetBytes(32);
  118.                 encryptor.IV = pdb.GetBytes(16);
  119.                 using (MemoryStream ms = new MemoryStream())
  120.                 {
  121.                     using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
  122.                     {
  123.                         cs.Write(clearBytes, 0, clearBytes.Length);
  124.                         cs.Close();
  125.                     }
  126.                     clearText = Convert.ToBase64String(ms.ToArray());
  127.                 }
  128.             }
  129.             return clearText;
  130.         }
  131.         public static string Decrypt(string cipherText, string passPhrase = EncryptionKey)
  132.         {
  133.             cipherText = cipherText.Replace(" ", "+");
  134.             byte[] cipherBytes = Convert.FromBase64String(cipherText);
  135.             using (Aes encryptor = Aes.Create())
  136.             {
  137.                 Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(passPhrase, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
  138.                 encryptor.Key = pdb.GetBytes(32);
  139.                 encryptor.IV = pdb.GetBytes(16);
  140.                 using (MemoryStream ms = new MemoryStream())
  141.                 {
  142.                     using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
  143.                     {
  144.                         cs.Write(cipherBytes, 0, cipherBytes.Length);
  145.                         cs.Close();
  146.                     }
  147.                     cipherText = Encoding.Unicode.GetString(ms.ToArray());
  148.                 }
  149.             }
  150.             return cipherText;
  151.         }
  152.     }
  153.  
  154.     public static class EncryptionForUrl
  155.     {
  156.         private const string EncryptionKey = "gabs1234"; // Strictly 8 characters
  157.  
  158.         private static byte[] key = { };
  159.         private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
  160.  
  161.         public static string Encrypt(string clearText, string passPhrase = EncryptionKey)
  162.         {
  163.             passPhrase = FixPassphrase(passPhrase);
  164.  
  165.             try
  166.             {
  167.                 key = System.Text.Encoding.UTF8.GetBytes(passPhrase);
  168.                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  169.                 byte[] inputByteArray = Encoding.UTF8.GetBytes(clearText);
  170.                 MemoryStream ms = new MemoryStream();
  171.                 CryptoStream cs = new CryptoStream(ms,
  172.                   des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
  173.                 cs.Write(inputByteArray, 0, inputByteArray.Length);
  174.                 cs.FlushFinalBlock();
  175.                 return System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(ms.ToArray())); //.Replace('+', '-').Replace('/', '_'));
  176.             }
  177.             catch (Exception e)
  178.             {
  179.                 return e.Message;
  180.             }
  181.         }
  182.  
  183.         public static string Decrypt(string cipherText, string passPhrase = EncryptionKey)
  184.         {
  185.             passPhrase = FixPassphrase(passPhrase);
  186.  
  187.             cipherText = System.Web.HttpUtility.UrlDecode(cipherText); //.Replace('-', '+').Replace('_', '/');
  188.             byte[] inputByteArray = new byte[cipherText.Length + 1];
  189.             try
  190.             {
  191.                 key = System.Text.Encoding.UTF8.GetBytes(passPhrase);
  192.                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  193.                 inputByteArray = Convert.FromBase64String(cipherText);
  194.                 MemoryStream ms = new MemoryStream();
  195.                 CryptoStream cs = new CryptoStream(ms,
  196.                   des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
  197.                 cs.Write(inputByteArray, 0, inputByteArray.Length);
  198.                 cs.FlushFinalBlock();
  199.                 System.Text.Encoding encoding = System.Text.Encoding.UTF8;
  200.                 return encoding.GetString(ms.ToArray());
  201.             }
  202.             catch (Exception e)
  203.             {
  204.                 return e.Message;
  205.             }
  206.         }
  207.  
  208.         private static string FixPassphrase(string passPhrase)
  209.         {
  210.             if (passPhrase.Length > 8)
  211.                 passPhrase = new string(passPhrase.Take(8).ToArray());
  212.             else if (passPhrase.Length > 0 && passPhrase.Length < 8)
  213.                 passPhrase = passPhrase + (new String('0', 8 - passPhrase.Length));
  214.             else if (string.IsNullOrWhiteSpace(passPhrase))
  215.                 passPhrase = EncryptionKey;
  216.  
  217.             return passPhrase;
  218.         }
  219.  
  220.     }
  221.  
  222.     public static class EncodingForBase64
  223.     {
  224.         public static string Encode(string plainText)
  225.         {
  226.             var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
  227.             return System.Convert.ToBase64String(plainTextBytes);
  228.         }
  229.  
  230.         public static string Decode(string base64EncodedData)
  231.         {
  232.             var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
  233.             return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
  234.         }
  235.     }
  236. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement