CSharp examples for Security:Password
Encodes the password.
using System.Threading.Tasks; using System.Text; using System.Security.Cryptography; using System.Linq; using System.Collections.Generic; using System;/* w ww. j a v a 2s. co m*/ public class Main{ /// <summary> /// Encodes the password. /// </summary> /// <param name="Message">The message.</param> /// <returns></returns> public static string EncodePassword(string Message) { byte[] Results; System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding(); string Passphrase = "secret"; // Step 1. We hash the passphrase using MD5 // We use the MD5 hash generator as the result is a 128 bit byte array // which is a valid length for the TripleDES encoder we use below MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider(); byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase)); // Step 2. Create a new TripleDESCryptoServiceProvider object TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider(); // Step 3. Setup the encoder TDESAlgorithm.Key = TDESKey; TDESAlgorithm.Mode = CipherMode.ECB; TDESAlgorithm.Padding = PaddingMode.PKCS7; // Step 4. Convert the input string to a byte[] byte[] DataToEncrypt = UTF8.GetBytes(Message); // Step 5. Attempt to encrypt the string try { ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor(); Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length); } finally { // Clear the TripleDes and Hashprovider services of any sensitive information TDESAlgorithm.Clear(); HashProvider.Clear(); } // Step 6. Return the encrypted string as a base64 encoded string return Convert.ToBase64String(Results); } }