Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace MyApp.CryptographyAPI
- {
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Security.Cryptography;
- using PWDTK_DOTNET45;
- /// <summary>
- /// This class contains all general Cryptography functionality
- /// </summary>
- public static class Cryptography
- {
- /// <summary>
- /// This is our encryption key
- /// </summary>
- 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 };
- /// <summary>
- /// This is the initialization vector used for our encrypting and decrypting
- /// </summary>
- private static byte[] vector = { 11, 28, 24, 7, 41, 12, 25, 66, 201, 55, 196, 74, 91, 4, 144, 165 };
- /// <summary>
- /// Transforms for performing encryption and decryption
- /// </summary>
- private static ICryptoTransform encryptorTransform, decryptorTransform;
- /// <summary>
- /// UTF8 Encoder used to encode text
- /// </summary>
- private static System.Text.UTF8Encoding utfEncoder;
- /// <summary>
- /// Initializes static members of the <see cref="Cryptography"/> class.
- /// </summary>
- static Cryptography()
- {
- // This is our encryption method
- RijndaelManaged rm = new RijndaelManaged();
- // Create an encryptor and a decryptor using our encryption method, key, and vector.
- encryptorTransform = rm.CreateEncryptor(key, vector);
- decryptorTransform = rm.CreateDecryptor(key, vector);
- // Used to translate bytes to text and vice versa
- utfEncoder = new System.Text.UTF8Encoding();
- }
- /// <summary>
- /// Generate an Encryption Key
- /// </summary>
- /// <returns>Encryption Key</returns>
- public static byte[] GenerateEncryptionKey()
- {
- // Generate a key and return it
- RijndaelManaged rm = new RijndaelManaged();
- rm.GenerateKey();
- return rm.Key;
- }
- /// <summary>
- /// Generates a unique encryption Vector
- /// </summary>
- /// <returns>Initialization Vector</returns>
- public static byte[] GenerateEncryptionVector()
- {
- RijndaelManaged rm = new RijndaelManaged();
- rm.GenerateIV();
- return rm.IV;
- }
- /// <summary>
- /// Encrypts a string of text
- /// </summary>
- /// <param name="textToEncrypt">The text to encrypt</param>
- /// <returns>The encrypted text string</returns>
- public static string EncryptString(string textToEncrypt)
- {
- return ByteArrayToString(Encrypt(textToEncrypt));
- }
- /// <summary>
- /// Decrypts an encrypted string
- /// </summary>
- /// <param name="textToDecrypt">the encrypted text</param>
- /// <returns>decrypted text string</returns>
- public static string DecryptString(string textToDecrypt)
- {
- return Decrypt(StringToByteArray(textToDecrypt));
- }
- /// <summary>
- /// Converts a string to a byte array. NOTE: Normally we'd create a Byte Array
- /// from a string using an ASCII encoding (like so).
- /// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
- /// return encoding.GetBytes(string);
- /// However, this results in character values that cannot be passed in a URL. So, instead, I just
- /// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
- /// </summary>
- /// <param name="stringToConvertToByteArray">The string to convert to a byte array</param>
- /// <returns>a byte array derived from a string</returns>
- public static byte[] StringToByteArray(string stringToConvertToByteArray)
- {
- if (string.IsNullOrEmpty(stringToConvertToByteArray))
- {
- throw new Exception("Invalid string value in stringToConvertToByteArray");
- }
- byte val;
- byte[] byteArray = new byte[stringToConvertToByteArray.Length / 3];
- int i = 0;
- int j = 0;
- do
- {
- val = byte.Parse(stringToConvertToByteArray.Substring(i, 3));
- byteArray[j++] = val;
- i += 3;
- }
- while (i < stringToConvertToByteArray.Length);
- return byteArray;
- }
- /// <summary>
- /// Converts a byte array to a string
- /// </summary>
- /// <param name="byteArrayToConvertToString">The byte array to convert</param>
- /// <returns>string converted from a byte array</returns>
- public static string ByteArrayToString(byte[] byteArrayToConvertToString)
- {
- byte val;
- string returnVal = string.Empty;
- for (int i = 0; i <= byteArrayToConvertToString.GetUpperBound(0); i++)
- {
- val = byteArrayToConvertToString[i];
- if (val < (byte)10)
- {
- returnVal += "00" + val.ToString();
- }
- else if (val < (byte)100)
- {
- returnVal += "0" + val.ToString();
- }
- else
- {
- returnVal += val.ToString();
- }
- }
- return returnVal;
- }
- /// <summary>
- /// Gets a series of random characters to use as a salt value in a hashing algorithm
- /// </summary>
- /// <param name="saltLength">How many characters the random salt string should be</param>
- /// <returns>A random series of characters</returns>
- public static string GetRandomSalt(int saltLength)
- {
- return ByteArrayToString(PWDTK.GetRandomSalt(saltLength));
- }
- /// <summary>
- /// Creates a hash of a string (a password, generally)
- /// </summary>
- /// <param name="salt">The salt to apply to the text before hashing</param>
- /// <param name="plainTextPassword">The plain text to perform the hash on</param>
- /// <returns>A hashed version of the string passed in</returns>
- public static string HashPassword(string salt, string plainTextPassword)
- {
- byte[] saltBytes = StringToByteArray(salt);
- byte[] hashedPasswordBytes = PWDTK.PasswordToHash(saltBytes, plainTextPassword, 8000);
- return ByteArrayToString(hashedPasswordBytes);
- }
- /// <summary>
- /// Compares a plain text password to a hashed version
- /// </summary>
- /// <param name="salt">The salt that was used to hash the password</param>
- /// <param name="plainTextPassword">The password in plain text</param>
- /// <param name="hashedPassword">The hashed version of the password</param>
- /// <returns>result of the password to hashed password comparison</returns>
- public static bool ComparePasswordToHash(string salt, string plainTextPassword, string hashedPassword)
- {
- byte[] saltBytes = StringToByteArray(salt);
- byte[] hashedPasswordBytes = StringToByteArray(hashedPassword);
- return PWDTK.ComparePasswordToHash(saltBytes, plainTextPassword, hashedPasswordBytes, 8000);
- }
- /// <summary>
- /// Encrypts a string and returns it in byte array format
- /// </summary>
- /// <param name="textToEncrypt">The text string value to encrypt</param>
- /// <returns>The encrypted text string in byte array format</returns>
- private static byte[] Encrypt(string textToEncrypt)
- {
- // Translates our text value into a byte array
- byte[] bytes = utfEncoder.GetBytes(textToEncrypt);
- byte[] encryptedTextBytes = null;
- // Used to stream the data in and out of the CryptoStream
- MemoryStream memoryStream = new MemoryStream();
- lock (memoryStream)
- {
- // We will have to write the unencrypted bytes to the stream,
- // then read the encrypted result back from the stream.
- CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptorTransform, CryptoStreamMode.Write);
- lock (cryptoStream)
- {
- cryptoStream.Write(bytes, 0, bytes.Length);
- cryptoStream.FlushFinalBlock();
- cryptoStream.Close();
- memoryStream.Position = 0;
- encryptedTextBytes = new byte[memoryStream.Length];
- memoryStream.Read(encryptedTextBytes, 0, encryptedTextBytes.Length);
- // Clean up
- memoryStream.Close();
- }
- }
- return encryptedTextBytes;
- }
- /// <summary>
- /// Decrypts a string that is in a byte array format
- /// </summary>
- /// <param name="encryptedTextBytes">The encrypted text in byte array format</param>
- /// <returns>decrypted string value</returns>
- private static string Decrypt(byte[] encryptedTextBytes)
- {
- byte[] decryptedTextBytes = null;
- MemoryStream encryptedTextStream = new MemoryStream();
- lock (encryptedTextStream)
- {
- CryptoStream decryptedTextStream = new CryptoStream(encryptedTextStream, decryptorTransform, CryptoStreamMode.Write);
- lock (decryptedTextStream)
- {
- decryptedTextStream.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
- decryptedTextStream.FlushFinalBlock();
- encryptedTextStream.Position = 0;
- decryptedTextBytes = new byte[encryptedTextStream.Length];
- encryptedTextStream.Read(decryptedTextBytes, 0, decryptedTextBytes.Length);
- decryptedTextStream.Close();
- encryptedTextStream.Close();
- }
- }
- System.Diagnostics.Debug.WriteLine("Decrypted String: " + utfEncoder.GetString(decryptedTextBytes));
- return utfEncoder.GetString(decryptedTextBytes);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement