如何将生成的IV从加密到解密方法

时间:2016-04-16 15:14:33

标签: c# c#-4.0 encryption

我不想用用户给定的密码播种IV。问题是,如果我已经创建了使用生成的IV进行加密的方法,那么无论如何我可以保存生成的IV,使其进入解密方法,而不将其保存到数据库中。

private void EncryptFile(string inputFile,string outputFile, string pass_input){

        try
       {
            MessageBox.Show("FLAG 1");
            UTF8Encoding UE = new UTF8Encoding();
            //Represents a UTF-8 encoding of unicode characters

            string password = pass_input;
            // passed password through user input

            byte[] key = UE.GetBytes(password);
            //password parsed into bytes

            string cryptFile = outputFile;
            FileStream FScrypt = new FileStream(cryptFile, FileMode.Create);
            //FScrypt is created where it creates a file to save output

            RijndaelManaged RMcrypto = new RijndaelManaged();
            //RMcrypto is created where new instance of RijndaelManaged Class is initialized

            RMcrypto.GenerateIV();
            CryptoStream cs = new CryptoStream(FScrypt, RMcrypto.CreateEncryptor(key,RMcrypto.IV), CryptoStreamMode.Write);
            //CreateEncryptor from RMcrypto creates a symmetric Rijndael Encryptor object with specified key

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);
            //fsIn Opens the input file
            MessageBox.Show("FLAG 2");
            int data;

            while ((data = fsIn.ReadByte()) != -1)
                //will read input file opened by fsIn
                cs.WriteByte((byte)data);
            MessageBox.Show("FLAG 3");

            fsIn.Close();
            cs.Close();
            FScrypt.Close();
       catch(Exception ex)
       {
          MessageBox.Show("Failed");
       }
}

private void DecryptFile(string inputFile, string outputFile, string pass_input)
    {
        try
        {
            string password = pass_input; // Taking password input and storing in local string. 

            UTF8Encoding UE = new UTF8Encoding()  //UnicodeEncoding Object UTF8
            byte[] key = UE.GetBytes(password); // converting password to bytes

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); // Opens the file

            RijndaelManaged RMCrypto = new RijndaelManaged(); //new RijndaelMaaged object

            CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, **"RMCrypto.IV"**), CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(outputFile, FileMode.Create);

            int data;

            while ((data = cs.ReadByte()) != -1)
               fsOut.WriteByte((byte)data);

            fsOut.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Failed");
        }
    }

1 个答案:

答案 0 :(得分:2)

一个使用/接受的方法是将IV添加到加密数据中,IV不需要保密。