如何用WPF制作简单的加密解密

cs 复制代码
<Window x:Class="加密解密.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:加密解密"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Button x:Name="buttion" Content="AES加密" HorizontalAlignment="Left" Margin="226,0,0,0" VerticalAlignment="Center" Height="51" Width="89" Click="buttion_Click"/>
        <Button x:Name="buttion2" Content="AES解密" HorizontalAlignment="Left" Margin="380,0,0,0" VerticalAlignment="Center" Height="51" Width="90" Click="buttion2_Click"/>
        <TextBox x:Name="textbox1" FontSize="30" HorizontalAlignment="Left" Margin="226,34,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="307" Height="51"/>
        <TextBox x:Name="textbox2" FontSize="20" HorizontalAlignment="Left" Margin="226,107,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="326" Height="50"/>
        <Button x:Name="button3" Content="DES加密" HorizontalAlignment="Left" Margin="226,274,0,0" VerticalAlignment="Top" Height="45" Width="89" Click="button3_Click"/>
        <Button x:Name="button4" Content="DES解密" HorizontalAlignment="Left" Margin="380,274,0,0" VerticalAlignment="Top" Height="45" Width="90" Click="button4_Click"/>
        <Button x:Name="button5" Content="RSA加密" HorizontalAlignment="Left" Margin="226,352,0,0" VerticalAlignment="Top" Height="47" Width="89" Click="button5_Click"/>
        <Button x:Name="button6" Content="RSA解密" HorizontalAlignment="Left" Margin="380,345,0,0" VerticalAlignment="Top" Height="54" Width="90" Click="button6_Click"/>

    </Grid>
</Window>

//使用之前需要在app.config文件中添加如下代码

<appSettings>

<add key="DESKEY" value="12345678"/>
<add key="AESKEY" value="12345678abcdefgh"/>
</appSettings>

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using 加密解密.EncryptTool;

namespace 加密解密
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

         }

        private void buttion_Click(object sender, RoutedEventArgs e)
        {
            textbox2.Text = AESHelper.Encrypt(textbox1.Text);
        }

        private void buttion2_Click(object sender, RoutedEventArgs e)
        {
            textbox1.Text = AESHelper.Decrypt(textbox2.Text);
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            textbox2.Text = DESHelper.Encrypt(textbox1.Text);
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            textbox1.Text = DESHelper.Decrypt(textbox2.Text);
        }

       

       
    }
}

需要添加一下代码

AESHelper

cs 复制代码
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace 加密解密.EncryptTool
{
    public static class AESHelper
    {
        private static readonly string keyString = ConfigurationManager.AppSettings["AESKEY"];
        // 它使用128、192或256位密钥
        private static readonly byte[] Key = Encoding.UTF8.GetBytes(keyString); // 16字节密钥
        private static readonly byte[] IV = Encoding.UTF8.GetBytes(keyString);  // 16字节初始化向量

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string data)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

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

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(data);
                        }
                        return Convert.ToBase64String(msEncrypt.ToArray());
                    }
                }
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">密文</param>
        /// <returns>明文</returns>
        public static string Decrypt(string data)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

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

                byte[] bytes = Convert.FromBase64String(data);

                using (MemoryStream msDecrypt = new MemoryStream(bytes))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            return srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }

    }
}

DESHelper

cs 复制代码
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace 加密解密.EncryptTool
{
    public static class DESHelper
    {
        //注意:在 引用上面右键 添加System.Configuration; 引用
        private static readonly string keyString = ConfigurationManager.AppSettings["DESKEY"];
        // 它使用56位密钥
        private static readonly byte[] Key = Encoding.UTF8.GetBytes(keyString); // 8字节密钥
        private static readonly byte[] IV = Encoding.UTF8.GetBytes(keyString);  // 8字节初始化向量

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string data)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                MemoryStream ms = new MemoryStream();
                CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
                byte[] toEncrypt = Encoding.UTF8.GetBytes(data);
                encStream.Write(toEncrypt, 0, toEncrypt.Length);
                encStream.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">密文</param>
        /// <returns>明文</returns>
        public static string Decrypt(string data)
        {
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] dataArray = Convert.FromBase64String(data);
                MemoryStream ms = new MemoryStream();
                CryptoStream decStream = new CryptoStream(ms, des.CreateDecryptor(Key, IV), CryptoStreamMode.Write);
                decStream.Write(dataArray, 0, dataArray.Length);
                decStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}

MD5Helper

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace 加密解密.EncryptTool
{
    public static class MD5Helper
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string data)
        {
            // MD5它将任意长度的数据转换为128位的哈希值。
            using (var md5 = MD5.Create())
            {
                byte[] bytes = Encoding.ASCII.GetBytes(data);
                byte[] hashBytes = md5.ComputeHash(bytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }

    }
}

RSAHelper

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace 加密解密.EncryptTool
{
    public static class RSAHelper
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string data)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                byte[] encrypted = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
                return Convert.ToBase64String(encrypted);
            }
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">密文</param>
        /// <returns>明文</returns>
        public static string Decrypt(string data)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                byte[] decrypted = rsa.Decrypt(Encoding.UTF8.GetBytes(data), false);
                return Encoding.UTF8.GetString(decrypted);
            }
        }
    }
}

SHAHelper

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace 加密解密.EncryptTool
{
    public static class SHAHelper
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">明文</param>
        /// <returns>密文</returns>
        public static string Encrypt(string data)
        {
            byte[] plainBytes = Encoding.UTF8.GetBytes(data);
            // 包括SHA-1、SHA-256、SHA-384和SHA-512。相比于MD5,SHA系列算法更安全。
            using (SHA256 cryptoProvider = new SHA256CryptoServiceProvider())
            {
                byte[] hashBytes = cryptoProvider.ComputeHash(plainBytes);
                StringBuilder hashBuilder = new StringBuilder();
                foreach (byte b in hashBytes)
                {
                    hashBuilder.Append(b.ToString("x2"));
                }
                return hashBuilder.ToString();
            }
        }
    }
}

效果展示

相关推荐
2601_962174172 天前
Redis 简介
数据库·redis·wpf
SamChan903 天前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf
SamChan903 天前
Python+OpenCV检测PDF翻译后排版偏移:像素级格式一致性验证
python·opencv·ai·pdf·wpf
FuckPatience4 天前
WPF 拿到控件的最初样式,修改获得焦点样式
wpf
主宰者4 天前
【WPF】MainWindow前添加加载窗口,发现加载过程中有白色无内容窗口闪烁一下的解决方案
wpf
Vae_Mars4 天前
WPF中的ControlTemplate(控件模板)
wpf
SamChan904 天前
Python+ReportLab自动生成PDF翻译质量审计报告:从数据到可视化的完整方案
开发语言·python·ai·pdf·wpf
circuitsosk4 天前
多智能体协同在能源数据分析中的实践:分配-执行-校验闭环架构设计
python·数据分析·wpf·能源·并行计算·多智能体系统·agent协作
weixin199701080165 天前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
hh9506 天前
gent Plan x DeepSeek Harness:多 Agent 协作场景下的中央编排实践
人工智能·wpf·adg·火山引擎·agent plan·adg成都社区