简体   繁体   English

读取字节数组与将字节数组写入File不一致

[英]Reading byte array are inconsistent with writing byte array into File

so my problem is simple. 所以我的问题很简单。 I want to Encrypt some text and write it to File like byte of array and than i need read the content of the File and get like parametr to another method which Decrypt that byte of array to string. 我想加密一些文本并将其像数组的字节一样写入文件,然后我需要读取文件的内容,然后像参数化另一个方法一样,将数组的那个字节解密为字符串。 Method Encrypt and Decrypt work fine i try it but when i use byte array from FILE it thrown Exception. 我尝试使用方法Encrypt和Decrypt正常工作,但是当我使用FILE中的字节数组时会抛出异常。

private static byte[] EncryptString(string text,byte[] key,byte[] vektor)
    {
        byte[] array=null;
        // Check arguments.
        if (text == null || text.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (vektor == null || vektor.Length <= 0)
            throw new ArgumentNullException("Vektor");
        try
        {
            using (DESCryptoServiceProvider provider = new DESCryptoServiceProvider())
            {
                provider.Key = key;
                provider.IV = vektor;
                using (MemoryStream memory = new MemoryStream())
                {
                    using (CryptoStream crypto = new CryptoStream(memory, provider.CreateEncryptor(provider.Key, provider.IV), CryptoStreamMode.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(crypto))
                        {
                            writer.WriteLine(text);
                        }
                    }
                    array = memory.ToArray();
                }
            }
        }
        catch (ArgumentNullException e)
        {
            Console.WriteLine("Error in EncryptString  {0}", e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error in EncryptString  {0}", e.Message);
        }
        return array;
    }

This method Ecnrypt byte array to string 该方法将加密字节数组转换为字符串

private static string DecryptByte(byte[] text, byte[] key, byte[] vektor)
    {
        string result = null;
        // Check arguments.
        if (text == null || text.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (key == null || key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (vektor == null || vektor.Length <= 0)
            throw new ArgumentNullException("Key");
        try
        {
            using (DESCryptoServiceProvider provider = new DESCryptoServiceProvider())
            {
                provider.Key=key;
                provider.IV=vektor;
                using (MemoryStream memory = new MemoryStream(text))
                {
                    using (CryptoStream crypto = new CryptoStream(memory, provider.CreateDecryptor(provider.Key, provider.IV), CryptoStreamMode.Read))
                    {
                        using (StreamReader read = new StreamReader(crypto))
                        { 
                            result=read.ReadToEnd();
                        }
                    }
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("Error in DecryptByte:{0}"+e.Message);
        }
        return result;
    }

Well i save the encrypt text and then when button is pushed 好吧,我保存加密文本,然后按下按钮时

private void buttonDecrypt_Click(object sender, RoutedEventArgs e)
    {
        byte[] text=null,helper=null;
        string result = null;
        try
        {
            using (FileStream filestream = File.OpenRead(path))
            {
                helper = new byte[filestream.Length];
                filestream.Read(helper, 0, (int)filestream.Length);
            }
                    using (DESCryptoServiceProvider provider = new DESCryptoServiceProvider())
                    {
                        result = DecryptByte(helper, provider.Key, provider.IV);
                    }
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error v ButtonDecrypt.{0}_____{1}",ex.Message,ex.Data);
        }
    }

So my problem is that data which i read from File is not the same and in DecryptByte thrown Exception. 所以我的问题是我从File中读取的数据不一样,并且在DecryptByte中引发了异常。 Could you help me? 你可以帮帮我吗? EDIT yeah Exception message is Invalid Data EDIT YES Exception message is Invalid Data

The code in your buttonDecrypt_Click you don't initialize the Key and the IV properties of your Decryptor. buttonDecrypt_Click中的代码不会初始化Decryptor的Key和IV属性。
I suspect that this is the cause of your exception. 我怀疑这是您例外的原因。

Moreover, I think you have another problem in the crypting and decrypting methods. 而且,我认为您在加密和解密方法上还有另一个问题。 DESCryptoServiceProvider is a wrapper around a SymmetricAlgorithm. DESCryptoServiceProvider是SymmetricAlgorithm的包装器。 This means that it encrypts bytes in blocks of equal size. 这意味着它将加密大小相等的块中的字节。 So the input data needs to be an exact multiple of the block size. 因此,输入数据必须是块大小的精确倍数。 This isn't going to happen all the time. 这不会一直发生。 Then padding needs to be used. 然后需要使用填充

provider.Padding = PaddingMode.PKCS7;

will ensure a correct block size in encrypted bytes (also needed in decrypting of course) 将确保以加密字节为单位的正确块大小(当然,解密时也需要)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM