C#理论-使用 C# WPF 实现图片和文字的加密与解密

引言

在开发过程中,保护敏感信息的安全性是非常重要的。本文将介绍如何使用 C# WPF 来对图片和文字进行加密和解密。我们将使用对称加密算法(如 AES)来实现这一功能。

前提条件

  • 安装 Visual Studio 2019 或更高版本。
  • 创建一个新的 WPF 应用程序项目。

第一步:创建用户界面

我们将创建一个简单的 WPF 用户界面,包含用于选择文件的按钮、显示结果的文本框和执行加密/解密操作的按钮。

1. 打开 MainWindow.xaml 文件
,并添加以下 XAML 代码来设计用户界面:
<Window x:Class="EncryptionApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Encryption and Decryption" Height="400" Width="600">
    <Grid>
        <Button Name="btnSelectFile" Content="Select File" Width="100" Height="30" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Click="btnSelectFile_Click"/>
        <Button Name="btnEncrypt" Content="Encrypt" Width="100" Height="30" HorizontalAlignment="Left" Margin="120,10,0,0" VerticalAlignment="Top" Click="btnEncrypt_Click"/>
        <Button Name="btnDecrypt" Content="Decrypt" Width="100" Height="30" HorizontalAlignment="Left" Margin="230,10,0,0" VerticalAlignment="Top" Click="btnDecrypt_Click"/>
        <TextBox Name="txtResult" Margin="10,50,10,10" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto" AcceptsReturn="True"/>
    </Grid>
</Window>

 

第二步:实现加密和解密功能

1. 打开 MainWindow.xaml.cs 文件,并添加以下代码:
using Microsoft.Win32;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows;

namespace EncryptionApp
{
    public partial class MainWindow : Window
    {
        private string filePath;
        private readonly string key = "b14ca5898a4e4133bbce2ea2315a1916"; // 32-byte key for AES-256

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == true)
            {
                filePath = openFileDialog.FileName;
                txtResult.Text = "Selected file: " + filePath;
            }
        }

        private void btnEncrypt_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                byte[] encryptedData = File.ReadAllBytes(filePath);
                string encryptedText = EncryptData(encryptedData, key);
                txtResult.Text = "Encrypted Text: " + encryptedText;
            }
            else
            {
                MessageBox.Show("Please select a file first.");
            }
        }

        private void btnDecrypt_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                string encryptedText = File.ReadAllText(filePath);
                byte[] decryptedData = DecryptData(encryptedText, key);
                File.WriteAllBytes(filePath + "_decrypted", decryptedData);
                txtResult.Text = "File decrypted and saved as: " + filePath + "_decrypted";
            }
            else
            {
                MessageBox.Show("Please select a file first.");
            }
        }

        private string EncryptData(byte[] data, string key)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(key);
                aesAlg.IV = new byte[16]; // Initialization vector with 0s

                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(data, 0, data.Length);
                        csEncrypt.FlushFinalBlock();
                        return Convert.ToBase64String(msEncrypt.ToArray());
                    }
                }
            }
        }

        private byte[] DecryptData(string encryptedText, string key)
        {
            byte[] cipherText = Convert.FromBase64String(encryptedText);

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(key);
                aesAlg.IV = new byte[16]; // Initialization vector with 0s

                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (var msDecrypt = new MemoryStream(cipherText))
                {
                    using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] decryptedData = new byte[cipherText.Length];
                        int decryptedByteCount = csDecrypt.Read(decryptedData, 0, decryptedData.Length);
                        Array.Resize(ref decryptedData, decryptedByteCount);
                        return decryptedData;
                    }
                }
            }
        }
    }
}

第三步:测试应用程序

  1. 运行你的 WPF 应用程序。
  2. 点击“Select File”按钮,选择一个图片文件或文本文件。
  3. 点击“Encrypt”按钮进行加密,结果将显示在文本框中。
  4. 点击“Decrypt”按钮进行解密,解密后的文件将保存到与原文件相同的目录,文件名为原文件名加上后缀“_decrypted”。

结论

通过本文,你已经学会了如何使用 C# WPF 实现对图片和文字的加密与解密。我们使用了 AES 对称加密算法来保证数据的安全性。这只是一个基本的实现,你可以根据需求进一步扩展和优化代码,例如处理更复杂的文件格式、添加异常处理等。希望这篇文章能为你的开发工作提供帮助。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值