文件读取中的填充问题 [英] Padding problem in File reading

查看:41
本文介绍了文件读取中的填充问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我是C#的新手,我正在尝试将数据加密到文件中,以后再将该数据用于许可目的.我正在使用Visual Studio文档示例进行加密和解密.

EncryptTextToFile()用于将文本加密到文件.以后DecryptTextFromFile()用于从文件解密.现在发生的事情是,第一个函数创建了文件,然后当DecryptTextFromFile()将其变为红色时,它将确切显示最初存储的内容.

注释EncryptTextToFile()并且仅使用解密功能对已经存储的文件进行解密时,发生以下错误:

Hello,

I am new to C# and I am trying to encrypt data to a file and later use that data for licencing purpose. I am using visual studio documentation example for encryption and decryption purposes.

EncryptTextToFile() is used to encrypt text to file. Later DecryptTextFromFile() is used to decrypt from file. Now what happens is that first function creates the file and then when it is red by DecryptTextFromFile() it shows exactly what was initially stored.

When EncryptTextToFile() is commented and only decrypting function is used to decrypted an already stored file following error occured:

An error occurred: Padding is invalid and cannot be removed.



这是代码:



Here is the code:

using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

class RijndaelSample
{

    static void Main()
    {
        try
        {
            // Create a new Rijndael object to generate a key
            // and initialization vector (IV).
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a string to encrypt.
            string sData = "BFEBFBFF00020652#0000";
            string FileName = "system.txt";

            // Encrypt text to a file using the file name, key, and IV.
            //EncryptTextToFile(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV);

            // Decrypt the text from a file using the file name, key, and IV.
            string Decrypted_text = DecryptTextFromFile(FileName, RijndaelAlg.Key, RijndaelAlg.IV);
            char []computer_id=new char[16];
            for (int K = 0; K < 16; K++)
            {
                computer_id[K] = Decrypted_text[K];
            }
           Int64 counts = 1000 * (Convert.ToInt64(Decrypted_text[17]) -48)+ 100 * (Convert.ToInt64(Decrypted_text[18])-48) + 10 * (Convert.ToInt64(Decrypted_text[19])-48) + (Convert.ToInt64(Decrypted_text[20])-48);
                    
                // Display the decrypted string to the console.
           Console.WriteLine(Decrypted_text);
Console.WriteLine(counts);
           Console.WriteLine(Convert.ToInt64(Decrypted_text[17]));
           Console.WriteLine(Convert.ToInt64(Decrypted_text[18]));
           Console.WriteLine(Convert.ToInt64(Decrypted_text[19]));
           Console.WriteLine(Convert.ToInt64(Decrypted_text[20]));
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }

    public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file.
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new Rijndael object.
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RijndaelAlg.CreateEncryptor(Key, IV),
                CryptoStreamMode.Write);

            // Create a StreamWriter using the CryptoStream.
            StreamWriter sWriter = new StreamWriter(cStream);

            try
            {
                // Write the data to the stream 
                // to encrypt it.
                sWriter.WriteLine(Data);
            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
            }
            finally
            {
                // Close the streams and
                // close the file.
                sWriter.Close();
                cStream.Close();
                fStream.Close();
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
        }

    }

    public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
    {
        try
        {
            // Create or open the specified file. 
            FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);

            // Create a new Rijndael object.
            Rijndael RijndaelAlg = Rijndael.Create();

            // Create a CryptoStream using the FileStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cStream = new CryptoStream(fStream,
                RijndaelAlg.CreateDecryptor(Key, IV),
                CryptoStreamMode.Read);

            // Create a StreamReader using the CryptoStream.
            StreamReader sReader = new StreamReader(cStream);

            string val = null;

            try
            {
                // Read the data from the stream 
                // to decrypt it.
                val = sReader.ReadLine();
               // val = sReader.ReadToEnd();
            


            }
            catch (Exception e)
            {
                Console.WriteLine("An error occurred: {0}", e.Message);
            }
            finally
            {

                // Close the streams and
                // close the file.
                sReader.Close();
                cStream.Close();
                fStream.Close();
            }
           
            // Return the string. 
            return val;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
    }
}



请帮助我解决此问题.



Kindly help me solve this problem.

推荐答案

问题是(我想)这行
The problem is (I suppose) the line
Rijndael RijndaelAlg = Rijndael.Create();


每次调用都会生成一个新密钥.当您需要解密以前加密的文件时,必须提供用于加密该文件的完全相同的密钥.


It generates a fresh key everytime is called. When you need to decrypt a previously encrypted file you must provide exactly the same key used for encrypting it.




在程序开始时,您将创建一个新的Rijndael实例,并使用其密钥和iv进行加密/解密.因此,当您在THE SAME运行中同时使用这两个功能时,将使用THE SAME密钥/iv对进行加密和解密.

如果分别浏览它们,则使用不同的键/iv对,因为Rijndael.Create()每次都会创建随机值,因此您会调用它.在第一次运行时保存密钥和向量,并在随后的运行中加载它们,一切都会好起来.

干杯
于尔根

-
如果这样可以节省您一些时间,请通过投票将其退还
Hi,

at the start of your program you create a new Rijndael-instance and use it''s key and iv for en-/decryption. Thus, when you go through both functions in THE SAME run, you use THE SAME key/iv-pair for en- and for decryption.

If you go through them separately, you use different key/iv-pairs, as Rijndael.Create() creates random values each time, you call it. Save both key and vector on the first run and load them on subsequent runs and all will be fine.

Cheers
Jürgen

--
If this saved you some time, give some it back by voting


谢谢你们俩.问题已解决.
Thanks to both of you. The problem is resolved.


这篇关于文件读取中的填充问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆