VS中用C#编写一个DES(或3DES)加解密的Windows应用程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了VS中用C#编写一个DES(或3DES)加解密的Windows应用程序相关的知识,希望对你有一定的参考价值。

窗体中设三个TextBox,用来输入八字节的明文(或密文)、密钥和输出加密(或解密)后的数据(都是十六进制数据);设两个Button,分别为加密和解密。初学者求码,谢谢!
谢谢1.2楼的回答!可是我新手却实现不了。而且想要的是输入输出都为十六进制的数,想做一个相当于一个十六制的运算器。我最终的目的是通过这个学习,新添加一些异或等运算制作达到方便工作所需的计算器。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ZU14

public partial class Form1 : Form

public Form1()

InitializeComponent();


//ZU14.DES des = new ZU14.DES();
ZU14.DES des = null;

private void btn_jiami_Click(object sender, EventArgs e)

textBox2.Text = des.Encrypt(textBox1.Text);
// MessageBox.Show("加密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);


private void btn_jiemi_Click(object sender, EventArgs e)

textBox3.Text = des.Decrypt(textBox2.Text);
//MessageBox.Show("解密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);


private void btn_wjjiami_Click(object sender, EventArgs e)

OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = @"d:\";
open.Filter = "文本文件(*.txt,*.doc,*.xls)|*.txt;*.doc;*.xls";
if (open.ShowDialog()== DialogResult.OK)

des.EncryptFile(open.FileName, open.FileName);
MessageBox.Show("加密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);




private void btn_wjjiemi_Click(object sender, EventArgs e)

OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = @"d:\";
open.Filter = "文本文件(*.txt,*.doc,*.xls)|*.txt;*.doc;*.xls";
if (open.ShowDialog() == DialogResult.OK)

des.DecryptFile(open.FileName);
MessageBox.Show("解密成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);




private void button1_Click(object sender, EventArgs e)

zifu.setmisi1 = textBox4.Text.Trim();
zifu.setmisi2 = textBox5.Text.Trim();
des = new ZU14.DES();



上面的代码是窗体的
下面是调用的两个类的
using System;
using System.Collections.Generic;
using System.Text;

namespace ZU14

class zifu

private static string misi1;
private static string misi2;
public static string getmisi1

get

return misi1;


public static string setmisi1

set

misi1 = value;


public static string getmisi2

get

return misi2;


public static string setmisi2

set

misi2 = value;





using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Collections;
using System.Data;
using System.Windows.Forms;

namespace ZU14

class DES


string iv =zifu.getmisi1; //"1234的yza";
string key = zifu.getmisi2;//"123在yzb";

/// <summary>
/// DES加密偏移量,必须是>=8位长的字符串
/// </summary>
public string IV

get return iv;
set iv = value;


/// <summary>
/// DES加密的私钥,必须是8位长的字符串
/// </summary>
public string Key

get return key;
set key = value;


/// <summary>
/// 对字符串进行DES加密
/// </summary>
/// <param name="sourceString">待加密的字符串</param>
/// <returns>加密后的BASE64编码的字符串</returns>
public string Encrypt(string sourceString)

byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())

byte[] inData = Encoding.Default.GetBytes(sourceString);
try

using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))

cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();


return Convert.ToBase64String(ms.ToArray());

catch

throw;




/// <summary>
/// 对DES加密后的字符串进行解密
/// </summary>
/// <param name="encryptedString">待解密的字符串</param>
/// <returns>解密后的字符串</returns>
public string Decrypt(string encryptedString)

byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

using (MemoryStream ms = new MemoryStream())

byte[] inData = Convert.FromBase64String(encryptedString);
try

using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))

cs.Write(inData, 0, inData.Length);
cs.FlushFinalBlock();


return Encoding.Default.GetString(ms.ToArray());

catch

throw;




/// <summary>
/// 对文件内容进行DES加密
/// </summary>
/// <param name="sourceFile">待加密的文件绝对路径</param>
/// <param name="destFile">加密后的文件保存的绝对路径</param>
public void EncryptFile(string sourceFile, string destFile)

if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile);

byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] btFile = File.ReadAllBytes(sourceFile);

using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))

try

using (CryptoStream cs = new CryptoStream(fs, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))

cs.Write(btFile, 0, btFile.Length);
cs.FlushFinalBlock();


catch

// throw;

finally

fs.Close();




/// <summary>
/// 对文件内容进行DES加密,加密后覆盖掉原来的文件
/// </summary>
/// <param name="sourceFile">待加密的文件的绝对路径</param>
public void EncryptFile(string sourceFile)

EncryptFile(sourceFile, sourceFile);


/// <summary>
/// 对文件内容进行DES解密
/// </summary>
/// <param name="sourceFile">待解密的文件绝对路径</param>
/// <param name="destFile">解密后的文件保存的绝对路径</param>
public void DecryptFile(string sourceFile, string destFile)

if (!File.Exists(sourceFile)) throw new FileNotFoundException("指定的文件路径不存在!", sourceFile);

byte[] btKey = Encoding.Default.GetBytes(key);
byte[] btIV = Encoding.Default.GetBytes(iv);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] btFile = File.ReadAllBytes(sourceFile);

using (FileStream fs = new FileStream(destFile, FileMode.Create, FileAccess.Write))

try

using (CryptoStream cs = new CryptoStream(fs, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))

cs.Write(btFile, 0, btFile.Length);
cs.FlushFinalBlock();


catch

// MessageBox.Show(ex.Message);
//throw;

finally

fs.Close();




/// <summary>
/// 对文件内容进行DES解密,加密后覆盖掉原来的文件
/// </summary>
/// <param name="sourceFile">待解密的文件的绝对路径</param>
public void DecryptFile(string sourceFile)

DecryptFile(sourceFile, sourceFile);




有什么看不明白的,再联系我,我的账号就是我的QQ
参考技术A 这是csdn上高手 周公 的博文(DES加密解密),你看看,很有价值。

地址:http://blog.csdn.net/zhoufoxcn/archive/2007/01/29/1497095.aspx

里面只是加密解密的源代码 ,你要winform的,直接将这些加密解密代码放到你的winform程序里面就行,将要加密的字符串从你的textbox种获取就行。

C#的DES文件加解密工具类

using System;

using System.Collections.Generic;

using System.Text;

using System.Security.Cryptography;

using System.IO;

namespace www.xinduofen.com

{

    class FileDES

    {

        ///

        /// 加密文件随机数生成

        ///

        private static RandomNumberGenerator rand = new RNGCryptoServiceProvider();

        private const ulong FC_TAG = 0xFC010203040506CF;

        private const int BUFFER_SIZE = 32 * 1024;

        ///

        /// 异常内部处理类

        ///

        private class CryptoHelpException : ApplicationException

        {

            public CryptoHelpException(string msg) : base(msg) { }

        }

        ///

        /// 加密文件,此方法不对异常进行处理,需要调用方进行捕获

        ///

        /// 待加密文件

        /// 加密后输出文件

        /// 加密密码

        /// 方法未产生任何异常 - 成功

        public static void EncryptFile(string inFile, string outFile, string password)

        {

            using (FileStream fin = File.OpenRead(inFile),

                fout = File.OpenWrite(outFile))

            {

                // 获取IV和salt

                byte[] IV = GenerateRandomBytes(16);

                byte[] salt = GenerateRandomBytes(16);

                // 创建加密对象

                SymmetricAlgorithm sma = FileDES.CreateRijndael(password, salt);

                sma.IV = IV;

                // 在输出文件开始部分写入IV和salt

                fout.Write(IV, 0, IV.Length);

                fout.Write(salt, 0, salt.Length);

                // 创建散列加密

                HashAlgorithm hasher = SHA256.Create();

                long lSize = fin.Length; // 输入文件长度

                byte[] bytes = new byte[BUFFER_SIZE]; // 缓存

                int read = -1; // 输入文件读取数量

                int value = 0;

                using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),

                    chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))

                {

                    BinaryWriter bw = new BinaryWriter(cout);

                    bw.Write(lSize);

                    bw.Write(FC_TAG);

                    // 读写字节块到加密流缓冲区

                    while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)

                    {

                        cout.Write(bytes, 0, read);

                        chash.Write(bytes, 0, read);

                        value += read;

                    }

                    // 关闭加密流

                    chash.Flush();

                    chash.Close();

                    // 读取散列

                    byte[] hash = hasher.Hash;

                    // 输入文件写入散列

                    cout.Write(hash, 0, hash.Length);

                    // 关闭文件流

                    cout.Flush();

                    cout.Close();

                }

            }

        }

        ///

        /// 解密文件,此方法不对异常进行处理,需要调用方进行捕获

        ///

        /// 待解密文件

        /// 解密后输出文件

        /// 解密密码

        /// 方法未产生任何异常 - 成功

        public static void DecryptFile(string inFile, string outFile, string password)

        {

            // 创建打开文件流

            using (FileStream fin = File.OpenRead(inFile),

                fout = File.OpenWrite(outFile))

            {

                int size = (int)fin.Length;

                byte[] bytes = new byte[BUFFER_SIZE];

                int read = -1;

                int value = 0;

                int outValue = 0;

                byte[] IV = new byte[16];

                fin.Read(IV, 0, 16);

                byte[] salt = new byte[16];

                fin.Read(salt, 0, 16);

                SymmetricAlgorithm sma = FileDES.CreateRijndael(password, salt);

                sma.IV = IV;

                value = 32;

                long lSize = -1;

                // 创建散列对象, 校验文件

                HashAlgorithm hasher = SHA256.Create();

                using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),

                    chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))

                {

                    // 读取文件长度

                    BinaryReader br = new BinaryReader(cin);

                    lSize = br.ReadInt64();

                    ulong tag = br.ReadUInt64();

                    if (FC_TAG != tag)

                        throw new CryptoHelpException("文件被破坏");

                    long numReads = lSize / BUFFER_SIZE;

                    long slack = (long)lSize % BUFFER_SIZE;

                    for (int i = 0; i < numReads; ++i)

                    {

                        read = cin.Read(bytes, 0, bytes.Length);

                        fout.Write(bytes, 0, read);

                        chash.Write(bytes, 0, read);

                        value += read;

                        outValue += read;

                    }

                    if (slack > 0)

                    {

                        read = cin.Read(bytes, 0, (int)slack);

                        fout.Write(bytes, 0, read);

                        chash.Write(bytes, 0, read);

                        value += read;

                        outValue += read;

                    }

                    chash.Flush();

                    chash.Close();

                    fout.Flush();

                    fout.Close();

                    byte[] curHash = hasher.Hash;

                    // 获取比较和旧的散列对象

                    byte[] oldHash = new byte[hasher.HashSize / 8];

                    read = cin.Read(oldHash, 0, oldHash.Length);

                    if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))

                        throw new CryptoHelpException("文件被破坏");

                }

                if (outValue != lSize)

                    throw new CryptoHelpException("文件大小不匹配");

            }

        }

        ///

        /// 创建加密对象

        ///

        /// 密码

        /// 密钥salt

        /// 加密对象

        private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)

        {

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);

            SymmetricAlgorithm sma = Rijndael.Create();

            sma.KeySize = 256;

            sma.Key = pdb.GetBytes(32);

            sma.Padding = PaddingMode.PKCS7;

            return sma;

        }

        ///

        /// 检验两个Byte数组是否相同

        ///

        /// Byte数组

        /// Byte数组

        /// true-相等

        private static bool CheckByteArrays(byte[] b1, byte[] b2)

        {

            if (b1.Length == b2.Length)

            {

                for (int i = 0; i < b1.Length; ++i)

                {

                    if (b1[i] != b2[i])

                        return false;

                }

                return true;

            }

            return false;

        }

        ///

        /// 生成指定长度的随机Byte数组

        ///

        /// Byte数组长度

        /// 随机Byte数组

        private static byte[] GenerateRandomBytes(int count)

        {

            byte[] bytes = new byte[count];

            rand.GetBytes(bytes);

            return bytes;

        }

    }

}

文章出自:越康体育

以上是关于VS中用C#编写一个DES(或3DES)加解密的Windows应用程序的主要内容,如果未能解决你的问题,请参考以下文章

java 与 c# 3des 加解密

6. Java 加解密技术系列之 3DES

怎么用C#解密 Java写的3des加密 ~~~~密钥是48位的。

python的des和3des加解密

DES3DES 加解密;MAC算法

3DES加解密示例