次のコードを使用して、デスクトップにあるテキスト ファイルを暗号化できます。
private void btnEncrypt_Click(object sender, EventArgs e)
{
//EncryptFile();
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All Files (*.*)|";
dialog.InitialDirectory = @"Desktop";
dialog.Title = "Please select a file to encrypt.";
dialog.ShowDialog();
inputFile = dialog.FileName;
outputFile = inputFile;
string password = @"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
これはうまく機能しますが、同じテキストファイルを復号化しようとしても何も起こりません。何が起こっているのかを知らせるエラーメッセージはスローされません。復号化には次のコードを使用します
private void btnDecrypt_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All Files (*.*)|";
dialog.InitialDirectory = @"Desktop";
dialog.Title = "Please select a file to decrypt.";
dialog.ShowDialog();
inputFile = dialog.FileName; // "C:\\Users\\daniel\\Desktop\\text.txt";
outputFile = inputFile;
string password = @"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
誰でも助けることができますか?