Advertisement
Demonslay335

Encrypt Bytes C#

Aug 28th, 2016
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.74 KB | None | 0 0
  1. public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
  2.         {
  3.             byte[] encryptedBytes = null;
  4.             // Static salt
  5.             byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
  6.             using (MemoryStream ms = new MemoryStream())
  7.             {
  8.                 using (RijndaelManaged AES = new RijndaelManaged())
  9.                 {
  10.                     AES.KeySize = 256;
  11.                     AES.BlockSize = 128;
  12.  
  13.                     // Thousand iterations of RFC2898 on the password to derive the key
  14.                     var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
  15.                     AES.Key = key.GetBytes(AES.KeySize / 8);
  16.                     AES.IV = key.GetBytes(AES.BlockSize / 8);
  17.  
  18.                     AES.Mode = CipherMode.CBC;
  19.  
  20.                     // Write encrypted bytes to stream
  21.                     using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
  22.                     {
  23.                         cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
  24.                         cs.Close();
  25.                     }
  26.                     encryptedBytes = ms.ToArray();
  27.                 }
  28.             }
  29.  
  30.             return encryptedBytes;
  31.         }
  32.  
  33. public byte[] EncryptBytes(byte[] bytesToBeEncrypted, string password)
  34.         {
  35.  
  36.             // Get bytes from string
  37.             byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
  38.  
  39.             // Hash the password with SHA256
  40.             passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
  41.  
  42.             // AES encrypt bytes
  43.             byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
  44.  
  45.             return bytesEncrypted;
  46.  
  47.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement