C# 文件的加密和解密

    技术2024-11-04  13

    1.界面 2. 由密码生成key和iv

    /// <summary>根据提供的密码生成Key和IV</summary> public static void GenKeyIV(string password, out byte[] key, out byte[] iv) { using (Aes aes = Aes.Create()) { key = new byte[aes.Key.Length]; byte[] pwdBytes = Encoding.UTF8.GetBytes(password); for (int i = 0; i < pwdBytes.Length; i++) { key[i] = pwdBytes[i]; } iv = new byte[aes.IV.Length]; for (int i = 0; i < pwdBytes.Length; i++) { iv[i] = pwdBytes[i]; } } } /// <summary>根据提供的密码生成Key和IV</summary> public static void GenKeyIV(out byte[] key, out byte[] iv) { using (Aes aes = Aes.Create()) { key = aes.Key; iv = aes.IV; } }

    3. Click事件,传新旧地址,key,iv

    private void Button_Click(object sender, RoutedEventArgs e) { if (pwdBox1.Password.Length < 5) { MessageBox.Show("密码不能低于5位"); return; } byte[] key, iv; AesHelp.GenKeyIV(pwdBox1.Password, out key, out iv); //加密 string oldPath = "1.txt"; string newPath = "2.txt"; byte[] data1 = AesHelp.EncryptString(oldPath, key, iv, newPath); string encryptedString = Convert.ToBase64String(data1); textBlock1.Text += "\n加密后的字符串:" + encryptedString; //解密 //byte[] data2 = Convert.FromBase64String(encryptedString); string s = AesHelp.DescrptString(newPath, key, iv); textBlock1.Text += "\n解密后的字符串:" + s; }

    4. 利用StreamReader先进行旧文件的读取获得字符串,对字符串进行加密,写入新文件

    public static byte[] EncryptString(string oldPath, byte[] key, byte[] iv, string newPath) { FileStream fs1 = new FileStream(oldPath, FileMode.Open, FileAccess.ReadWrite); StreamReader sr = new StreamReader(fs1); string str = sr.ReadToEnd(); sr.Close(); fs1.Close(); byte[] encrypted; if (File.Exists(newPath)) { File.Delete(newPath); } FileStream fs2 = new FileStream(newPath, FileMode.OpenOrCreate, FileAccess.ReadWrite); using (Aes aesAlg = Aes.Create()) { ICryptoTransform encryptor = aesAlg.CreateEncryptor(key, iv); CryptoStream cs = new CryptoStream( fs2, encryptor, CryptoStreamMode.Write); using (StreamWriter sw = new StreamWriter(cs, Encoding.UTF8)) { sw.Write(str); } cs.Close(); fs2.Close(); } fs2 = new FileStream(newPath, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs2); encrypted = br.ReadBytes(10240); br.Close(); return encrypted; }

    5. 对新文件进行解密

    /// <summary>使用AES算法解密字符串</summary> public static string DescrptString(String newPath, byte[] key, byte[] iv) { string str = null; using (Aes aesAlg = Aes.Create()) { ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, iv); FileStream fs = new FileStream(newPath, FileMode.Open, FileAccess.Read); CryptoStream cs = new CryptoStream( fs, decryptor, CryptoStreamMode.Read); using (StreamReader sr = new StreamReader(cs, Encoding.UTF8)) { str = sr.ReadToEnd(); } cs.Close(); fs.Close(); } return str; }

    结果: 问题讨论: 第一次输出中文乱码,后来改了oldFile的编码格式为UTF-8,写入读取都使用UTF-8,实现

    Processed: 0.023, SQL: 9