UweOeder@Capricorn Ответов: 1

Проблема реализации шифрования/дешифрования надувного замка


I am trying to implement encryption and decryption with the bouncy castle library. In Method 1 I struggle to specify a padding and I cannot dynamically specify the encryption mode. In Method 2 I managed to specify a padding but I did not manage to specify an encryption mode so I guess it is using ECB. I took some random text file to encrypt and decrypt. But both methods seems to have an error. With Method 1 it seems to add extra bytes/characters of the original text like it was padding with the raw text. And with method 2 when it decrypts it does not display the full message there is text which is missing. So I tried to do a .DoFinal() function but that just gives me an error message which says Pad Block corrupted. There must somehow be a way of specifying a padding and a encryption mode, perhaps even dynamically. However most examples are in Java which do not directly translate to C#. All input welcome.

Что я уже пробовал:

<pre>
private void button1_Click(object sender, EventArgs e)
        {
            FileStream varFileStreamInput, varFileStreamOutput;
            Byte[] varInBuffer, varOutBuffer;
            varInBuffer = new Byte[16];
            varOutBuffer = new Byte[16];
            Int32 varBytesRead, varProcessedBytes;

            //Method.1
            //Key Generation with IV.
            PbeParametersGenerator varKeyGenerator = new Pkcs12ParametersGenerator(new Sha256Digest());            
            varKeyGenerator.Init(Encoding.ASCII.GetBytes(varPassword), Encoding.ASCII.GetBytes(varSalt), 10240);
            ParametersWithIV varParmWithIV = (ParametersWithIV)varKeyGenerator.GenerateDerivedParameters("AES128", 128, 128);

            //Init of Block Cipher with engine type and parameters but no padding.
            Org.BouncyCastle.Crypto.Modes.CbcBlockCipher varCBCBlckCpher = new CbcBlockCipher(new AesEngine());
            varCBCBlckCpher.Init(true, varParmWithIV);
            
            //Encrypt
            varFileStreamInput = new FileStream(@"C:\Temp12\Test1.txt", FileMode.Open);
            varFileStreamOutput = new FileStream(@"C:\Temp12\Test1.txt.enc", FileMode.Create);

            varBytesRead = varProcessedBytes = 0;
            while (varFileStreamInput.Position != varFileStreamInput.Length)
            {
                varBytesRead = varFileStreamInput.Read(varInBuffer, 0, 16);
                varProcessedBytes = varCBCBlckCpher.ProcessBlock(varInBuffer, 0, varOutBuffer, 0);
                varFileStreamOutput.Write(varOutBuffer, 0, varProcessedBytes);
            }            
            varFileStreamOutput.Flush();
            varFileStreamOutput.Close();
            varFileStreamInput.Close();


            //Open files again for decryption, to test if encryption worked correctly.
            varCBCBlckCpher.Init(false, varParmWithIV);
            varFileStreamInput = new FileStream(@"C:\Temp12\Test1.txt.enc", FileMode.Open);
            varFileStreamOutput = new FileStream(@"C:\Temp12\Test1.txt.dec", FileMode.Create);

            varBytesRead = varProcessedBytes = 0;
            while (varFileStreamInput.Position != varFileStreamInput.Length)
            {
                varBytesRead = varFileStreamInput.Read(varInBuffer, 0, 16);
                varProcessedBytes = varCBCBlckCpher.ProcessBlock(varInBuffer, 0, varOutBuffer, 0);
                varFileStreamOutput.Write(varOutBuffer, 0, varProcessedBytes);
            }            
            varFileStreamOutput.Flush();
            varFileStreamOutput.Close();
            varFileStreamInput.Close();

            //--------------------------------------------------------------------------------------------------------------------------

            //Method.2
            //Key Generation without IV.
            Org.BouncyCastle.Crypto.ICipherParameters varICphrParm = varKeyGenerator.GenerateDerivedParameters("AES128", 128);
            BufferedBlockCipher varBufferedBlockCipher = new PaddedBufferedBlockCipher(new AesEngine(), new Pkcs7Padding());
            varBufferedBlockCipher.Init(true, varICphrParm);

            varFileStreamInput = new FileStream(@"C:\Temp12\Test1.txt", FileMode.Open);
            varFileStreamOutput = new FileStream(@"C:\Temp12\Test2.txt.enc", FileMode.Create);

            varBytesRead = varProcessedBytes = 0;

            while (varFileStreamInput.Position != varFileStreamInput.Length)
            {
                varBytesRead = varFileStreamInput.Read(varInBuffer, 0, 16);
                varProcessedBytes = varBufferedBlockCipher.ProcessBytes(varInBuffer, varOutBuffer, 0);
                varFileStreamOutput.Write(varOutBuffer, 0, varProcessedBytes);
            }
            varFileStreamOutput.Flush();
            varFileStreamOutput.Close();
            varFileStreamInput.Close();

            //Open files again for decryption, to test if encryption worked correctly.
            varBufferedBlockCipher.Init(false, varICphrParm);

            varFileStreamInput = new FileStream(@"C:\Temp12\Test2.txt.enc", FileMode.Open);
            varFileStreamOutput = new FileStream(@"C:\Temp12\Test2.txt.dec", FileMode.Create);

            varBytesRead = varProcessedBytes = 0;

            while (varFileStreamInput.Position != varFileStreamInput.Length)
            {
                varBytesRead = varFileStreamInput.Read(varInBuffer, 0, 16);
                varProcessedBytes = varBufferedBlockCipher.ProcessBytes(varInBuffer, varOutBuffer, 0);
                varFileStreamOutput.Write(varOutBuffer, 0, varProcessedBytes);
            }
            //varOutBuffer = varBufferedBlockCipher.DoFinal(varInBuffer); <-- Error here Pad Block corrupted.
            //varFileStreamOutput.Write(varOutBuffer, 0, varProcessedBytes);

            varFileStreamOutput.Flush();
            varFileStreamOutput.Close();
            varFileStreamInput.Close();
        }

Gerry Schmitz

Является ли "надувной замок" обязательным требованием? Никаких других "более распространенных" вариантов?

UweOeder@Capricorn

Привет, Джерри Шмитц, я хотел бы использовать Bouncy Castle, так как в будущем я хотел бы использовать шифрование, отличное от AES, которое, насколько я знаю, является шифром по умолчанию, поддерживаемым Microsoft.

BillWoodruff

начните здесь: https://www.bouncycastle.org/csharp/resources.html

UweOeder@Capricorn

Привет, Билл Вудрафф, единственная ссылка на веб-странице, которую вы предоставили с примерами, отключилась. К сожалению, я не смог найти никаких примеров из этой ссылки.

BillWoodruff

Тогда продолжайте искать. Если вы не найдете текущих форумов или ресурсов "надувного замка", то можете рассмотреть другую альтернативу.

1 Ответов

Рейтинг:
2

UweOeder@Capricorn

Я протестировал приведенный ниже код, и он, похоже, работает для заполнения CBC и PKSC7, а также генератора ключей для ключа и IV.

FileStream varFileStreamInput, varFileStreamOutput;
            Byte[] varInBuffer, varOutBuffer;
            varInBuffer = new Byte[1000];
            varOutBuffer = new Byte[1000];
            Int32 varBytesRead;

            //Method.3
            //Key Generation with IV.
            PbeParametersGenerator varKeyGenerator = new Pkcs12ParametersGenerator(new Sha256Digest());
            varKeyGenerator.Init(Encoding.ASCII.GetBytes(varPassword), Encoding.ASCII.GetBytes(varSalt), 10240);
            ParametersWithIV varParmWithIV = (ParametersWithIV)varKeyGenerator.GenerateDerivedParameters("AES128", 128, 128);

            //Init of Block Cipher with engine type and parameters but no padding.
            Org.BouncyCastle.Crypto.BufferedBlockCipher varBufBlckCipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), new Pkcs7Padding());
            varBufBlckCipher.Init(true, varParmWithIV);

            //Encrypt
            varFileStreamInput = new FileStream(@"C:\Temp12\Test1.txt", FileMode.Open);
            varFileStreamOutput = new FileStream(@"C:\Temp12\Test3.txt.enc", FileMode.Create);

            varBytesRead = 0;
            while (varFileStreamInput.Position != varFileStreamInput.Length)
            {
                varBytesRead = varFileStreamInput.Read(varInBuffer, 0, 1000);
                varOutBuffer = varBufBlckCipher.ProcessBytes(varInBuffer, 0, varBytesRead); // ProcessBlock(varInBuffer, 0, varOutBuffer, 0);
                varFileStreamOutput.Write(varOutBuffer, 0, varOutBuffer.Length);
            }
            varOutBuffer = varBufBlckCipher.DoFinal();
            varFileStreamOutput.Write(varOutBuffer, 0, varOutBuffer.Length);

            varFileStreamOutput.Flush();
            varFileStreamOutput.Close();
            varFileStreamInput.Close();


            //Open files again for decryption, to test if encryption worked correctly.
            varBufBlckCipher.Init(false, varParmWithIV);
            varFileStreamInput = new FileStream(@"C:\Temp12\Test3.txt.enc", FileMode.Open);
            varFileStreamOutput = new FileStream(@"C:\Temp12\Test3.txt.dec", FileMode.Create);

            varBytesRead = 0;
            while (varFileStreamInput.Position != varFileStreamInput.Length)
            {
                varBytesRead = varFileStreamInput.Read(varInBuffer, 0, 1000);
                varOutBuffer = varBufBlckCipher.ProcessBytes(varInBuffer, 0, varBytesRead); // ProcessBlock(varInBuffer, 0, varOutBuffer, 0);
                varFileStreamOutput.Write(varOutBuffer, 0, varOutBuffer.Length);
            }
            varOutBuffer = varBufBlckCipher.DoFinal();
            varFileStreamOutput.Write(varOutBuffer, 0, varOutBuffer.Length);

            varFileStreamOutput.Flush();
            varFileStreamOutput.Close();
            varFileStreamInput.Close();