DES Encrypt password - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:Password

Description

DES Encrypt password

Demo Code


using System.Security.Cryptography;
using System.IO;/*from w  w  w.ja v a 2  s.c o m*/
using System.Text;
using System.Collections.Generic;
using System;

public class Main{
   public static string Encrypt(string password, string cleartext)
   {
      string password2 = "99999999968";
      
      string cipher;
      char[] key = new char[8];
      if (password.Length > 8)
      {
         password = password.Remove(8);
      }
      password.CopyTo(0, key, 0, password.Length);
      
      char[] iv = new char[8];
      if (password2.Length > 8)
      {
         password2 = password2.Remove(8);
      }
      password2.CopyTo(0, iv, 0, password2.Length);
      
      if (cleartext == null)
      {
         return string.Empty;
      }
      
      SymmetricAlgorithm serviceProvider = new DESCryptoServiceProvider();
      serviceProvider.Key = Encoding.ASCII.GetBytes(key);
      serviceProvider.IV = Encoding.ASCII.GetBytes(iv);
      
      MemoryStream memoryStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memoryStream, serviceProvider.CreateEncryptor(), CryptoStreamMode.Write);
      StreamWriter streamWriter = new StreamWriter(cryptoStream);
      
      streamWriter.Write(cleartext);
      streamWriter.Dispose();
      cryptoStream.Dispose();
      
      byte[] signData = memoryStream.ToArray();
      memoryStream.Dispose();
      serviceProvider.Clear();
      cipher = Convert.ToBase64String(signData);
      
      return cipher;
   }
}

Related Tutorials