Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Basic Rijndael (AES) encryption (See related posts)

   1  
   2  using System.IO;
   3  using System.Security.Cryptography;
   4   
   5              private static readonly byte[] SALT = new byte[] { 0x26, 0xdc, 0xff, 0x00, 0xad, 0xed, 0x7a, 0xee, 0xc5, 0xfe, 0x07, 0xaf, 0x4d, 0x08, 0x22, 0x3c };
   6   
   7              public static byte[] Encrypt(byte[] plain, string password)
   8              {
   9                  MemoryStream memoryStream;
  10                  CryptoStream cryptoStream;
  11                  Rijndael rijndael = Rijndael.Create();
  12                  Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);
  13                  rijndael.Key = pdb.GetBytes(32);
  14                  rijndael.IV = pdb.GetBytes(16);
  15                  memoryStream = new MemoryStream();
  16                  cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
  17                  cryptoStream.Write(plain, 0, plain.Length);
  18                  cryptoStream.Close();
  19                  return memoryStream.ToArray();
  20              }
  21              public static byte[] Decrypt(byte[] cipher, string password)
  22              {
  23                  MemoryStream memoryStream;
  24                  CryptoStream cryptoStream;
  25                  Rijndael rijndael = Rijndael.Create();
  26                  Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password, SALT);
  27                  rijndael.Key = pdb.GetBytes(32);
  28                  rijndael.IV = pdb.GetBytes(16);
  29                  memoryStream = new MemoryStream();
  30                  cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write);
  31                  cryptoStream.Write(cipher, 0, cipher.Length);
  32                  cryptoStream.Close();
  33                  return memoryStream.ToArray();
  34              }

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts