private static byte[] Decrypt(byte[] cipher, string password)
{
try
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Padding = PaddingMode.ISO10126;
byte[] ciphertextByte = cipher;
byte[] saltByte = Encoding.ASCII.GetBytes(password.Length.ToString());
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, saltByte);
ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(ciphertextByte);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainText = new byte[ciphertextByte.Length];
int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
memoryStream.Close();
cryptoStream.Close();
return plainText;
}
catch (Exception e)
{
throw new InvalidDataException("[" + e.ToString() + " : " + e.Message + "] Data corrupt");
}
}
private static byte[] Encrypt(byte[] input, string password)
{
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Padding = PaddingMode.ISO10126;
byte[] saltByte = Encoding.ASCII.GetBytes(password.Length.ToString());
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(password, saltByte);
ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(input, 0, input.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
encryptor.Dispose();
return cipherBytes;
}
public static void EncryptFile(string password, string fileName)
{
byte[] encryptedFile = Encrypt(File.ReadAllBytes(fileName), password);
File.WriteAllBytes(fileName, encryptedFile);
}
public static void DecryptFile(string fileName, string password)
{
byte[] decryptedFile = Decrypt(File.ReadAllBytes(fileName), password);
File.WriteAllBytes(fileName, decryptedFile);
}