C#将byte []发送到服务器,解密内容并将其作为byte []发送回客户端

时间:2018-12-07 07:40:35

标签: c# sockets encryption client-server file-transfer

我的问题如下:

我有一个通过套接字连接的客户端/服务器应用程序。我客户的任务是按字节发送文件到服务器。服务器获取字节,将其解密,然后将其发送回客户端,然后将其写入磁盘上的新文件中。

每次在此代码行出现服务器端异常(System.Security.Cryptography.Exception:填充无效且无法删除)时,我都会收到此消息:plaintext = sr.ReadToEnd();

有人可以帮助我解决我的问题吗?

这是解密代码:

public byte[] Dec(byte[] content, byte[] Key, byte[] IV, int fileLength, string filepath, int chunkSize, int bytesToRead)
    {
        byte[] contentDec;
        string plaintext = null;
        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;

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


            using (MemoryStream ms = new MemoryStream(content))
            {
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader sr = new StreamReader(cs))
                    {
                        plaintext = sr.ReadToEnd();
                        cs.FlushFinalBlock();
                    }
                    contentDec = encoding.GetBytes(plaintext);
                }
            }
        }
        return contentDec;
    }

这是我的加密代码:

    public byte[] Enc(byte[] content,byte[] Key, byte[] IV, int fileLength,string filepath, int chunkSize, int bytesToRead)
    {
        byte[] contentEnc;
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter sw = new StreamWriter(cs))
                    {
                        sw.Write(content);
                    }
                    contentEnc = ms.ToArray();
                }
            }
        }
        return contentEnc;
    }

在客户端,我这样调用加密方法

        int chunkSize = 1024;
        byte[] chunk = new byte[chunkSize];
        using (FileStream fileReader = new FileStream(plainPath, FileMode.Open, FileAccess.Read))
        using (FileStream filewriter = new FileStream(pathEncrypt, FileMode.Create, FileAccess.ReadWrite))
        using (BinaryReader binaryReader = new BinaryReader(fileReader))
        using (RijndaelManaged myRijndael = new RijndaelManaged())
        {
            myRijndael.GenerateKey();
            myRijndael.GenerateIV();
            Key = myRijndael.Key;
            IV = myRijndael.IV;
            int bytesToRead = (int)fileReader.Length;
            do
            {
                chunk = service.Enc(binaryReader.ReadBytes(chunkSize), Key, IV,(int)fileReader.Length, 
                    fileReader.Name, chunkSize, bytesToRead);
                filewriter.Write(chunk, 0, chunk.Length);
                bytesToRead -= chunkSize;
            } while (bytesToRead > 0);
        }

密钥和IV声明为私有字节[]

在客户端,我这样调用解密方法

        int chunkSize = 1024;
        byte[] chunk = new byte[chunkSize];
        using (FileStream fileReader = new FileStream(pathEncrypt, FileMode.Open, FileAccess.Read))
        using (FileStream filewriter = new FileStream(pathDecrypt, FileMode.Create, FileAccess.ReadWrite))
        using (BinaryReader binaryReader = new BinaryReader(fileReader))
        {
            int bytesToRead = (int)fileReader.Length;

            do
            {
                chunk = service.Dec(binaryReader.ReadBytes(chunkSize), Key, IV, (int)fileReader.Length, 
                    fileReader.Name, chunkSize, bytesToRead);
                filewriter.Write(chunk, 0, chunk.Length);
                bytesToRead -= chunkSize;
            } while (bytesToRead > 0);
        }

编辑:这是我在客户端和服务器之间的连接建立。

服务器:     var host = new ServiceHost(typeof(Service),                        新的Uri(“ net.pipe:// localhost”));

        host.AddServiceEndpoint(typeof(TiService),
                                new NetNamedPipeBinding(), "TestService");
        host.Open();
        Console.WriteLine("Server connection established...");
        Console.ReadKey();

客户:

var callback = new Callback();
var context = new InstanceContext(callback);
var pipeFactory =
new DuplexChannelFactory<TiService>(context,
new NetNamedPipeBinding(),
new EndpointAddress("net.pipe://localhost/TestService"));

service = pipeFactory.CreateChannel();
service.Connect();

1 个答案:

答案 0 :(得分:0)

您的问题开始于在加密中使用StreamWriter。它用于写文本文件,而不是任意文件。当您调用sw.Write(content)时,它仅调用content.ToString(),它返回“ System.Byte []”,而不是您可能期望的数组的每个字节。要解决此问题,只需编写CryptoStream,无需使用StreamWriter,如下所示:

using (var rijAlg = new AesCng())
{
    rijAlg.Key = Key;
    rijAlg.IV = IV;
    ICryptoTransform encryptor = rijAlg.CreateEncryptor();
    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(content, 0, content.Length);               
        }
        contentEnc = ms.ToArray();
    }
}

您可能注意到我使用AesCng而不是RijndaelManaged。为什么?因为在我的测试中它要快得多,并且除非您真的需要非标准块,否则使用RijndaelManaged没有任何好处。另外,我使用无参数的CreateEncryptor,因为无论如何您已经在前几行中设置了Key&IV。

解密中的处理相同。您不应该将它们视为文本,因此:

var buffer = new byte[content.Length]; //at first its size is actual size+padding

using (var rijAlg = new AesCng())
{
    rijAlg.Key = Key;
    rijAlg.IV = IV;

    ICryptoTransform decryptor = rijAlg.CreateDecryptor();

    using (MemoryStream ms = new MemoryStream(content))
    {
        using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
        {
            var actualSize = cs.Read(buffer, 0, content.Length);
            //we write the decrypted content to the buffer, and get the actual size

            Array.Resize(ref buffer, actualSize);
            //then we resize the buffer to the actual size
        }
    }
}
return buffer;

此外,您对Enc和Dec的使用不必要地复杂。它已经能够自己处理整个文件。因此,要加密文件,只需使用

var original = File.ReadAllBytes("originalPath");
var enc = Enc(original, rM.Key, rM.IV);
File.WriteAllBytes("encryptedPath", enc);

要解密文件,只需使用

var enc = File.ReadAllBytes("encryptedPath");
var dec = Dec(enc, rM.Key, rM.IV);
File.WriteAllBytes("decryptedPath", dec);

如您所见,我丢弃了Enc&Dec上的fileLength,filepath,chunkSize和bytesToRead,因为您当前的代码实际上并没有使用它们。我已经尝试过使用ASCII,Unicode和UTF-8上的短文本文件以及大型二进制文件进行代码编码,所有这些文件均已成功加密和解密,并且最终解密的文件具有相同的哈希值。

编辑:

将代码转换为直接的文件流写操作实际上使一切变得更加简单。

public static void Transform(string source, string target, ICryptoTransform transf)
{
    var bufferSize = 65536;
    var buffer = new byte[bufferSize];


    using (var sourceStream = new FileStream(source, FileMode.Open))
    {
        using (var targetStream = new FileStream(target, FileMode.OpenOrCreate))
        {
            using (CryptoStream cs = new CryptoStream(targetStream, transf, CryptoStreamMode.Write))
            {
                var bytesRead = 0;
                do
                {
                    bytesRead = sourceStream.Read(buffer, 0, bufferSize);
                    cs.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
        }

    }


}

public static void Enc(string source, byte[] Key, byte[] IV, string target)
{
    using (var rijAlg = new AesCng())
    {
        rijAlg.Key = Key;
        rijAlg.IV = IV;
        ICryptoTransform encryptor = rijAlg.CreateEncryptor();
        Transform(source, target, encryptor);
    }

}
public static void Dec(string source, byte[] Key, byte[] IV, string target)
{
    using (var rijAlg = new AesCng())
    {
        rijAlg.Key = Key;
        rijAlg.IV = IV;
        ICryptoTransform decryptor = rijAlg.CreateDecryptor();
        Transform(source, target, decryptor);
    }

}

用法是:

Enc(@"originalPath", key, iv, @"encryptedPath");
Dec(@"encrypedPath", key, iv, @"decryptedPath");