日期:2014-05-17  浏览次数:21258 次

c#异或的加密解密,本人计算机二级还没考的水平
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication10
{
    class Program//总之就是问题多多,求抱大腿,看了几小时了
    {
        static void Main(string[] args)
        {
            FileStream fs = new CzCryptStream("EncyptLetter.txt", FileMode.Create, "rose");//rose是干什么的,这个txt会被创建出来吗
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine("this is a letter from hollywood.外公家");
            sw.Close();
            fs = new FileStream("EncyptLetter.txt", FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            Console.WriteLine("加密文件内容:");
            while (!sr.EndOfStream)
                Console.WriteLine(sr.ReadLine());
            sr.Close();
            fs = new CzCryptStream("EncyptLetter.txt", FileMode.Open,"rose");
            sr = new StreamReader(fs);
            Console.WriteLine("\n解密文件内容:");
            while(!sr.EndOfStream)
               Console.WriteLine(sr.ReadLine());
            sr.Close();
            fs.Close();
        }
    }
    public class CzCryptStream : FileStream
    {
        private byte[] mkey;
        public CzCryptStream(string spath, FileMode fmode, string skey)//fmode干嘛吃的?各种搞不懂啊!
            : base(spath, fmode)
        {
            mkey = new byte[skey.Length];
            for (int i = 0; i < skey.Length; i++)
                mkey[i] = (byte)skey[i];
        }
        public override int ReadByte()
        {
            return base.ReadByte() ^ mkey[this.Position % mkey.Length];//Position我问度娘还是不知道什么意思啊,求解
        }
        public override void WriteByte(byte value)//这么多事件,主方法里没见调用,这是为什么?
        {
            value ^= mkey[this.Position % mkey.Length];
            base.WriteByte(value);
        }
        public override int Read(byte[] buffer, int offset, int count)
        {
            int iLen= base.Read(buffer, offset, count);
            for (int i = 0; i < iLen; i++)
            {
                buffer[i]^=mkey[(offset+i)%mkey.Length];
            }
            return iLen;
        }
        public override void Write(byte[] buffer, int offset, int count)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] ^= mkey[(offset + i) % mkey.Length];
            }
            base.Write(buffer, offset, count);
        }

    }
}

再问,这程序里的密钥怎么产生的??安全吗?有没有根据这个方法编个程序然后直接发送密文,由程序解密的程序?
...........

------解决方案--------------------
1."rose"是密钥
2.fmode是用于初始化FileStream
3.见FileStream.Position
4.FileStream会在写入时间接调用这些方法
5.密钥是那个rose,注意到这里密钥只能用ASCII字符
6.任何将密钥硬编码在程序中的行为都是愚蠢的
7.不想写到文件里的话,可以改为继承MemoryStream