Advertisement
jamauss

code for SO question

Apr 1st, 2013
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.60 KB | None | 0 0
  1. namespace MyApp.CryptographyAPI
  2. {
  3.     using System;
  4.     using System.Collections.Generic;
  5.     using System.Data;
  6.     using System.IO;
  7.     using System.Security.Cryptography;
  8.     using PWDTK_DOTNET45;
  9.  
  10.     /// <summary>
  11.     /// This class contains all general Cryptography functionality
  12.     /// </summary>
  13.     public static class Cryptography
  14.     {
  15.         /// <summary>
  16.         /// This is our encryption key
  17.         /// </summary>
  18.         private static byte[] key = { 24, 65, 55, 49, 48, 56, 48, 74, 76, 32, 49, 54, 55, 56, 66, 75, 56, 50, 56, 57, 57, 67, 74, 51, 52, 28, 49, 76, 65, 57, 49, 56 };
  19.  
  20.         /// <summary>
  21.         /// This is the initialization vector used for our encrypting and decrypting
  22.         /// </summary>
  23.         private static byte[] vector = { 11, 28, 24, 7, 41, 12, 25, 66, 201, 55, 196, 74, 91, 4, 144, 165 };
  24.  
  25.         /// <summary>
  26.         /// Transforms for performing encryption and decryption
  27.         /// </summary>
  28.         private static ICryptoTransform encryptorTransform, decryptorTransform;
  29.  
  30.         /// <summary>
  31.         /// UTF8 Encoder used to encode text
  32.         /// </summary>
  33.         private static System.Text.UTF8Encoding utfEncoder;
  34.  
  35.         /// <summary>
  36.         /// Initializes static members of the <see cref="Cryptography"/> class.
  37.         /// </summary>
  38.         static Cryptography()
  39.         {
  40.             // This is our encryption method
  41.             RijndaelManaged rm = new RijndaelManaged();
  42.  
  43.             // Create an encryptor and a decryptor using our encryption method, key, and vector.
  44.             encryptorTransform = rm.CreateEncryptor(key, vector);
  45.             decryptorTransform = rm.CreateDecryptor(key, vector);
  46.  
  47.             // Used to translate bytes to text and vice versa
  48.             utfEncoder = new System.Text.UTF8Encoding();
  49.         }
  50.  
  51.         /// <summary>
  52.         /// Generate an Encryption Key
  53.         /// </summary>
  54.         /// <returns>Encryption Key</returns>
  55.         public static byte[] GenerateEncryptionKey()
  56.         {
  57.             // Generate a key and return it
  58.             RijndaelManaged rm = new RijndaelManaged();
  59.            
  60.             rm.GenerateKey();
  61.             return rm.Key;
  62.         }
  63.  
  64.         /// <summary>
  65.         /// Generates a unique encryption Vector
  66.         /// </summary>
  67.         /// <returns>Initialization Vector</returns>
  68.         public static byte[] GenerateEncryptionVector()
  69.         {
  70.             RijndaelManaged rm = new RijndaelManaged();
  71.            
  72.             rm.GenerateIV();
  73.             return rm.IV;
  74.         }
  75.  
  76.         /// <summary>
  77.         /// Encrypts a string of text
  78.         /// </summary>
  79.         /// <param name="textToEncrypt">The text to encrypt</param>
  80.         /// <returns>The encrypted text string</returns>
  81.         public static string EncryptString(string textToEncrypt)
  82.         {
  83.             return ByteArrayToString(Encrypt(textToEncrypt));
  84.         }
  85.  
  86.         /// <summary>
  87.         /// Decrypts an encrypted string
  88.         /// </summary>
  89.         /// <param name="textToDecrypt">the encrypted text</param>
  90.         /// <returns>decrypted text string</returns>
  91.         public static string DecryptString(string textToDecrypt)
  92.         {
  93.             return Decrypt(StringToByteArray(textToDecrypt));
  94.         }
  95.  
  96.         /// <summary>
  97.         /// Converts a string to a byte array.  NOTE: Normally we'd create a Byte Array
  98.         /// from a string using an ASCII encoding (like so).
  99.         /// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  100.         /// return encoding.GetBytes(string);
  101.         /// However, this results in character values that cannot be passed in a URL.  So, instead, I just
  102.         /// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
  103.         /// </summary>
  104.         /// <param name="stringToConvertToByteArray">The string to convert to a byte array</param>
  105.         /// <returns>a byte array derived from a string</returns>
  106.         public static byte[] StringToByteArray(string stringToConvertToByteArray)
  107.         {
  108.             if (string.IsNullOrEmpty(stringToConvertToByteArray))
  109.             {
  110.                 throw new Exception("Invalid string value in stringToConvertToByteArray");
  111.             }
  112.  
  113.             byte val;
  114.             byte[] byteArray = new byte[stringToConvertToByteArray.Length / 3];
  115.             int i = 0;
  116.             int j = 0;
  117.             do
  118.             {
  119.                 val = byte.Parse(stringToConvertToByteArray.Substring(i, 3));
  120.                 byteArray[j++] = val;
  121.                 i += 3;
  122.             }
  123.             while (i < stringToConvertToByteArray.Length);
  124.  
  125.             return byteArray;
  126.         }
  127.  
  128.         /// <summary>
  129.         /// Converts a byte array to a string
  130.         /// </summary>
  131.         /// <param name="byteArrayToConvertToString">The byte array to convert</param>
  132.         /// <returns>string converted from a byte array</returns>
  133.         public static string ByteArrayToString(byte[] byteArrayToConvertToString)
  134.         {
  135.             byte val;
  136.             string returnVal = string.Empty;
  137.  
  138.             for (int i = 0; i <= byteArrayToConvertToString.GetUpperBound(0); i++)
  139.             {
  140.                 val = byteArrayToConvertToString[i];
  141.                 if (val < (byte)10)
  142.                 {
  143.                     returnVal += "00" + val.ToString();
  144.                 }
  145.                 else if (val < (byte)100)
  146.                 {
  147.                     returnVal += "0" + val.ToString();
  148.                 }
  149.                 else
  150.                 {
  151.                     returnVal += val.ToString();
  152.                 }
  153.             }
  154.  
  155.             return returnVal;
  156.         }
  157.  
  158.         /// <summary>
  159.         /// Gets a series of random characters to use as a salt value in a hashing algorithm
  160.         /// </summary>
  161.         /// <param name="saltLength">How many characters the random salt string should be</param>
  162.         /// <returns>A random series of characters</returns>
  163.         public static string GetRandomSalt(int saltLength)
  164.         {
  165.             return ByteArrayToString(PWDTK.GetRandomSalt(saltLength));
  166.         }
  167.  
  168.         /// <summary>
  169.         /// Creates a hash of a string (a password, generally)
  170.         /// </summary>
  171.         /// <param name="salt">The salt to apply to the text before hashing</param>
  172.         /// <param name="plainTextPassword">The plain text to perform the hash on</param>
  173.         /// <returns>A hashed version of the string passed in</returns>
  174.         public static string HashPassword(string salt, string plainTextPassword)
  175.         {
  176.             byte[] saltBytes = StringToByteArray(salt);
  177.             byte[] hashedPasswordBytes = PWDTK.PasswordToHash(saltBytes, plainTextPassword, 8000);
  178.             return ByteArrayToString(hashedPasswordBytes);
  179.         }
  180.  
  181.         /// <summary>
  182.         /// Compares a plain text password to a hashed version
  183.         /// </summary>
  184.         /// <param name="salt">The salt that was used to hash the password</param>
  185.         /// <param name="plainTextPassword">The password in plain text</param>
  186.         /// <param name="hashedPassword">The hashed version of the password</param>
  187.         /// <returns>result of the password to hashed password comparison</returns>
  188.         public static bool ComparePasswordToHash(string salt, string plainTextPassword, string hashedPassword)
  189.         {
  190.             byte[] saltBytes = StringToByteArray(salt);
  191.             byte[] hashedPasswordBytes = StringToByteArray(hashedPassword);
  192.             return PWDTK.ComparePasswordToHash(saltBytes, plainTextPassword, hashedPasswordBytes, 8000);
  193.         }
  194.  
  195.         /// <summary>
  196.         /// Encrypts a string and returns it in byte array format
  197.         /// </summary>
  198.         /// <param name="textToEncrypt">The text string value to encrypt</param>
  199.         /// <returns>The encrypted text string in byte array format</returns>
  200.         private static byte[] Encrypt(string textToEncrypt)
  201.         {
  202.             // Translates our text value into a byte array
  203.             byte[] bytes = utfEncoder.GetBytes(textToEncrypt);
  204.  
  205.             byte[] encryptedTextBytes = null;
  206.  
  207.             // Used to stream the data in and out of the CryptoStream
  208.             MemoryStream memoryStream = new MemoryStream();
  209.  
  210.             lock (memoryStream)
  211.             {
  212.                 // We will have to write the unencrypted bytes to the stream,
  213.                 // then read the encrypted result back from the stream.
  214.                 CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptorTransform, CryptoStreamMode.Write);
  215.                 lock (cryptoStream)
  216.                 {
  217.                     cryptoStream.Write(bytes, 0, bytes.Length);
  218.                     cryptoStream.FlushFinalBlock();
  219.                     cryptoStream.Close();
  220.  
  221.                     memoryStream.Position = 0;
  222.                     encryptedTextBytes = new byte[memoryStream.Length];
  223.                     memoryStream.Read(encryptedTextBytes, 0, encryptedTextBytes.Length);
  224.                    
  225.                     // Clean up
  226.                    
  227.                     memoryStream.Close();
  228.                 }
  229.  
  230.                
  231.             }
  232.             return encryptedTextBytes;
  233.         }
  234.  
  235.         /// <summary>
  236.         /// Decrypts a string that is in a byte array format
  237.         /// </summary>
  238.         /// <param name="encryptedTextBytes">The encrypted text in byte array format</param>
  239.         /// <returns>decrypted string value</returns>
  240.         private static string Decrypt(byte[] encryptedTextBytes)
  241.         {
  242.             byte[] decryptedTextBytes = null;
  243.             MemoryStream encryptedTextStream = new MemoryStream();
  244.             lock (encryptedTextStream)
  245.             {
  246.                 CryptoStream decryptedTextStream = new CryptoStream(encryptedTextStream, decryptorTransform, CryptoStreamMode.Write);
  247.                 lock (decryptedTextStream)
  248.                 {
  249.                     decryptedTextStream.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
  250.                     decryptedTextStream.FlushFinalBlock();
  251.                    
  252.  
  253.                     encryptedTextStream.Position = 0;
  254.                     decryptedTextBytes = new byte[encryptedTextStream.Length];
  255.                     encryptedTextStream.Read(decryptedTextBytes, 0, decryptedTextBytes.Length);
  256.                     decryptedTextStream.Close();
  257.                     encryptedTextStream.Close();
  258.                 }
  259.  
  260.                
  261.             }
  262.             System.Diagnostics.Debug.WriteLine("Decrypted String: " + utfEncoder.GetString(decryptedTextBytes));
  263.             return utfEncoder.GetString(decryptedTextBytes);
  264.         }
  265.     }
  266. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement