|
[attachimg]1428[/atta- private void Button_Click(object sender, RoutedEventArgs e)
- {
- string str1 = "明文.txt";
- string str2 = "密文.txt";
- if (p1.Password.Length<5)
- {
- MessageBox.Show("密码不能低于5位");
- return;
- }
- byte[] key, iv;
- aes.GenKeyIV(p1.Password, out key, out iv);
- string ss = "";
- FileStream fs = new FileStream(str1, FileMode.Open, FileAccess.Read);
- StreamReader sr = new StreamReader(fs);
- ss = sr.ReadToEnd();
- fs.Close();
- sr.Close();
- a1.Text = "原始字符串:" + ss;
- byte[] data1 = aes.EncryptString(str1, str2, key, iv);
- string encryptedString = Convert.ToBase64String(data1);
- a1.Text += "\n加密后的字符串:" + encryptedString;
- byte[] data2 = Convert.FromBase64String(encryptedString);
- string s = aes.DescrptString(data2, key, iv);
- a1.Text += "\n解密后的字符串:" + s;
- }
- public static byte[] EncryptString(string str1, string str2, byte[] key, byte[] iv) //使用AES算法加密字符串
- {
- string ss = "";
- FileStream fs = new FileStream(str1, FileMode.Open, FileAccess.Read);
- StreamReader sr = new StreamReader(fs);
- ss = sr.ReadToEnd();
- fs.Close();
- sr.Close();
- FileStream fs1 = new FileStream(str2, FileMode.Create, FileAccess.Write);
- using (Aes aesAlg = Aes.Create())
- {
- ICryptoTransform encryptor = aesAlg.CreateEncryptor(key, iv);
- CryptoStream cs = new CryptoStream(fs1, encryptor, CryptoStreamMode.Write);
- using (StreamWriter sw = new StreamWriter(cs))
- {
- sw.Write(ss);
- }
- cs.Close();
- fs1.Close();
- }
- fs1 = new FileStream(str2, FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fs1);
- byte[] encrypted = br.ReadBytes(10240);
- br.Close();
- fs1.Close();
- return encrypted;
- }
- public static string DescrptString(byte[] data, byte[] key, byte[] iv) //使用AES算法解密字符串
- {
- string str = "";
- using (Aes aesAlg = Aes.Create())
- {
- ICryptoTransform decryptor = aesAlg.CreateDecryptor(key, iv);
- MemoryStream ms = new MemoryStream(data);
- CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
- using (StreamReader sr = new StreamReader(cs))
- {
- str = sr.ReadToEnd();
- }
- cs.Close();
- ms.Close();
- }
- return str;
- }
- public static void GenKeyIV(string password, out byte[] key, out byte[] iv) //根据提供的密码生成key和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];
- }
- }
- }
- public static void GenKeyIV(out byte[] key, out byte[] iv) //随机生成Key和IV
- {
- using (Aes aes = Aes.Create())
- {
- key = aes.Key;
- iv = aes.IV;
- }
- }
复制代码 chimg] |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|