Encrypt and Decrypt password - CSharp Security

CSharp examples for Security:Cryptography

Description

Encrypt and Decrypt password

Demo Code

using System;/*from   w  w w. j a  v  a  2  s  .  c  o m*/
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using static System.Console;
using System.IO;
using System.Xml;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
class Program
{
   static void Main(string[] args)
   {
      string message = "this is a test";
      string password = "password";
      string cryptoText = Protector.Encrypt(message, password);
      WriteLine($"Encrypted text: {cryptoText}");
      string password2 = "password";
      try
      {
         string clearText = Protector.Decrypt(cryptoText, password2);
         WriteLine($"Decrypted text: {clearText}");
      }
      catch
      {
         WriteLine("Enable to decrypt because you entered the wrong password!");
      }
   }
}
public static class Protector
{
   private static readonly byte[] salt = Encoding.Unicode.GetBytes("7BANANAS");
   private static readonly int iterations = 2000;
   public static string Encrypt(string plainText, string password)
   {
      byte[] plainBytes = Encoding.Unicode.GetBytes(plainText);
      var aes = Aes.Create();
      var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
      aes.Key = pbkdf2.GetBytes(32); // set a 256-bit key
      aes.IV = pbkdf2.GetBytes(16); // set a 128-bit IV
      var ms = new MemoryStream();
      using (var cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
      {
         cs.Write(plainBytes, 0, plainBytes.Length);
      }
      return Convert.ToBase64String(ms.ToArray());
   }
   public static string Decrypt(string cryptoText, string password)
   {
      byte[] cryptoBytes = Convert.FromBase64String(cryptoText);
      var aes = Aes.Create();
      var pbkdf2 = new Rfc2898DeriveBytes(password, salt, iterations);
      aes.Key = pbkdf2.GetBytes(32);
      aes.IV = pbkdf2.GetBytes(16);
      var ms = new MemoryStream();
      using (var cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
      {
         cs.Write(cryptoBytes, 0, cryptoBytes.Length);
      }
      return Encoding.Unicode.GetString(ms.ToArray());
   }
}

Result


Related Tutorials