posts - 29,  comments - 103,  trackbacks - 0

有个同学要交作业,要求用c#做了一个。其实就是调用库函数实现的。
源程序   可执行文件
从来没有c#开发过,这次是第一次。感觉很容易上手,不过限制有点太多了。
印象比较深的有一下几点:
1.string 与 byte[]之间的转换。c#中好像没有强制类型转换(后经人指点确定是我不知道怎么转换)。我用了byte[] System.Text.ASCIIEncoding.ASCII.GetBytes(string);
2.文件的读写和保存创建好像方法有很多种。没有深入研究。在MSDN上找一个例子套用的。
3.对DES加密的整个程序过程也是在MSDN上搜的,然后自己读懂的。发现MSDN真的很全面,难怪有人说是Win开发的圣经。以后用微软的东西开发的疑问都应该先去MSDN上查。
4.对异常的处理。c#对异常的处理还是比较周到的。只要对相应的异常捕捉处理就行了。但是在try的作用域的问题上有点异或。应该在哪个地方进行try catch。是在子函数还是在总函数。有时会出现局部变量不可引用的问题。这个还没有深入研究。
下面是源代码。

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Security.Cryptography;
using System.IO;

namespace MyDES
{

    
/// <summary>
    
/// Form1 的摘要说明。
    
/// </summary>

    public class Form1 : System.Windows.Forms.Form
    
{    
        
自动生成的代码

        
private void button3_Click(object sender, System.EventArgs e)
        
{//加密
            string Key = this.textBox4.Text;
            
string IV = "12345678";//初始化向量设为"12345678"
            byte[] desKey=System.Text.ASCIIEncoding.ASCII.GetBytes( Key );
            
byte[] desIV=System.Text.ASCIIEncoding.ASCII.GetBytes( IV );
            
try
            
{
                
if(this.MyEncrypt(this.textBox1.Text,this.textBox2.Text,desKey,desIV))
                    MessageBox.Show(
"文件加密成功");
            }

            
catch(System.IO.FileNotFoundException)
            
{
                MessageBox.Show(
"Error!\n"+"输入文件不存在,请检查输入文件的路径。");
            }

            
catch(System.IO.IOException)
            
{
                MessageBox.Show(
"Error!\n"+"输出文件正在使用,请选择其他文件。\n如果问题依然存在,请关闭该程序,重新运行!");
            }

            
catch(System.Exception ee)
            
{
                System.Windows.Forms.MessageBox.Show(
"未知错误!请认真阅读一下说明:\n"+ee);
            }

        }



        
private void button5_Click(object sender, System.EventArgs e)
        
{//解密
            string Key = this.textBox4.Text;
            
string IV = "12345678";//初始化向量设为"12345678"
            byte[] desKey=System.Text.ASCIIEncoding.ASCII.GetBytes(Key);
            
byte[] desIV=System.Text.ASCIIEncoding.ASCII.GetBytes(IV);
            
try
            
{
                
if(this.MyDecrypt(this.textBox1.Text,this.textBox2.Text,desKey,desIV))
                    MessageBox.Show(
"文件解密成功");
            }

            
catch(System.IO.FileNotFoundException)
            
{
                MessageBox.Show(
"Error!\n"+"输入文件不存在,请检查输入文件的路径。"