/// <summary> /// Encrypts plaintext using the Encrypt-then-MAC (EtM) mode via the Rijndael cipher in /// CBC mode with a password derived HMAC SHA-512 salt. /// </summary> /// <param name="plaintext">The plaintext to encrypt.</param> /// <param name="password">The password to encrypt the plaintext with.</param> /// <param name="iv">The initialization vector. Must be 128-bits.</param> /// <param name="keySize">The cipher key size. 256-bit is stronger, but slower.</param> /// <returns>The EtM ciphertext.</returns> public static new byte[] Encrypt(byte[] plaintext, string password, byte[] iv, KeySize keySize) { // Generate AE keys var keyRing = AeKeyRing.Generate(password); // Encrypt the plaintext var ciphertext = Rijndael.Encrypt(plaintext, keyRing.CipherKey, iv, keySize); // Calculate the MAC from the ciphertext var mac = CalculateMac(ciphertext, keyRing.MacKey); // Append the MAC to the ciphertext var etmCiphertext = new byte[ciphertext.Length + mac.Length]; Buffer.BlockCopy(ciphertext, 0, etmCiphertext, 0, ciphertext.Length); Buffer.BlockCopy(mac, 0, etmCiphertext, ciphertext.Length, mac.Length); // IV + Cipher + MAC return(etmCiphertext); }
private void btnEncrypt_Click(object sender, EventArgs e) { string ToEncrypt; try { ToEncrypt = FilePath + lbFiles.SelectedItem.ToString(); } catch (Exception) { MessageBox.Show("You must select an item to encrypt or decrypt!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (string.IsNullOrWhiteSpace(txtPassword.Text)) { MessageBox.Show("You must enter a password to decrypt or encrypt files!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string Password = txtPassword.Text; string Output = FilePath + lbFiles.SelectedItem.ToString() + ".locked"; if (Path.GetExtension(ToEncrypt).ToLower() == ".locked") { MessageBox.Show("File is already encrypted!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } else { } Rijndael.Encrypt(ToEncrypt, Output, txtPassword.Text, KS); File.Delete(ToEncrypt); WriteToConsole("Encrypted file successfully"); }