用RC4加密txt文件A,密文写到文件B,但是读取密文文件B后对其解密则得不到明文,而是乱码用RC4加密txt文件A,密文直接解密,用Console.WriteLine();方法打在控制台上是正确显示的,所以,加密算法应该是没问题的,我想应该是编码的问题吧代码在下面这个是main方法的内容
        static void Main(string[] args)
        {
            string path1 = @"F:\aaa.txt";
            string path2 = @"F:\bbb.txt";
            FileStream fs = new FileStream(path1, FileMode.Open, FileAccess.Read);
            FileStream fs2 = new FileStream(path2, FileMode.Create, FileAccess.Write);
            byte[] fsbyte = new byte[fs.Length];
            string buffer;
            char[] pData = new char[10000];
            char[] S_Box1 = new char[256];    //S_Box1
            char[] S_Box2 = new char[256];    //S-Box2
            ulong len = (ulong)pData.Length;
            //密钥
            buffer = "abcde";
            char[] key = new char[128];
            key = buffer.ToCharArray();
            //
            fs.Read(fsbyte, 0, (int)fs.Length);
            buffer = System.Text.Encoding.Default.GetString(fsbyte);
            pData = buffer.ToCharArray();
            Console.WriteLine(pData);
            rc4.rc4_init(S_Box1, key, key.Length);//初始化
            rc4.rc4_crypt(S_Box1, pData, pData.Length);//加密
            buffer = pData.ToString();
            fsbyte = System.Text.Encoding.Default.GetBytes(pData);
            fs2.Write(fsbyte,0,fsbyte.Length);
            Console.ReadKey();
        }

解决方案 »

  1.   

    RC4
        class rc4
            {
                static public void swap<T>(ref T a, ref T b)
                {
                    T tmp;
                    tmp = a;
                    a = b;
                    b = tmp;
                }
                //--------------------------------------------------------            static public void rc4_init(char[] s_box, char[] key, int Len) //初始化
                {
                    int j = 0;
                    char[] k = new char[256];
                    for (int i = 0; i < 256; i++)
                    {
                        s_box[i] = (char)i;
                        k[i] = key[i % Len];
                    }
                    for (int i = 0; i < 256; i++)
                    {
                        j = (j + s_box[i] + k[i]) % 256;
                        swap(ref s_box[i], ref s_box[j]);
                    }
                }
                //--------------------------------------------------------
                static public void rc4_crypt(char[] s, char[] Data, int Len) //加解密
                {
                    int i = 0, j = 0, t = 0;
                    for (int k = 0; k < Len; k++)
                    {
                        i = (i + 1) % 256;
                        j = (j + s[i]) % 256;
                        swap(ref s[i], ref s[j]);
                        t = (s[i] + s[j]) % 256;
                        Data[k] ^= s[t];
                    }
                }
            }