/// <summary> /// Taken from https://stackoverflow.com/a/30821908 /// </summary> /// <param name="privateKey"></param> /// <param name="stream"></param> /// <param name="decryptedFileName"></param> public static void DecryptAES(RSACryptoServiceProvider privateKey, FileStream stream, string decryptedFileName) { try { using (RijndaelManaged AES = new RijndaelManaged()) { var data = ReadFully(stream, privateKey.KeySize / 8); var AESKey = privateKey.Decrypt(data, false); AES.Key = AESKey; var iv = ReadFully(stream, AES.BlockSize / 8); AES.IV = iv; using (var cs = new NotClosingCryptoStream(stream, AES.CreateDecryptor(), CryptoStreamMode.Read)) { using (FileStream fs = new FileStream(decryptedFileName, FileMode.Create, FileAccess.Write)) { cs.CopyTo(fs); } } } } catch (Exception e) { MessageBox.Show("Error while decrypting the file or writing to file." + Environment.NewLine + e.Message); return; } finally { stream.Seek(0, SeekOrigin.Begin); } }
public static void DecryptAndVerify(RSACryptoServiceProvider privateKey, RSACryptoServiceProvider publicKey, FileStream stream, string decryptedFileName) { byte[] sign = null; try { using (RijndaelManaged AES = new RijndaelManaged()) { var data = ReadFully(stream, privateKey.KeySize / 8); var AESKey = privateKey.Decrypt(data, false); AES.Key = AESKey; var iv = ReadFully(stream, AES.BlockSize / 8); AES.IV = iv; using (var cs = new NotClosingCryptoStream(stream, AES.CreateDecryptor(), CryptoStreamMode.Read)) { sign = ReadFully(cs, publicKey.KeySize / 8); using (FileStream fs = new FileStream(decryptedFileName, FileMode.Create, FileAccess.Write)) { cs.CopyTo(fs); } } } } catch (Exception e) { MessageBox.Show("Error while decrypting the file or writing to file." + Environment.NewLine + e.Message); return; } finally { stream.Seek(0, SeekOrigin.Begin); } //============// try { using (FileStream decrypted = new FileStream(decryptedFileName, FileMode.Open, FileAccess.Read, FileShare.None)) { if (publicKey.VerifyData(decrypted, sign, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1)) { MessageBox.Show("File sign is verified"); } else { MessageBox.Show("File is tempered"); } } } catch (Exception e) { MessageBox.Show("Error while verifying the signature." + Environment.NewLine + e.Message); return; } }