Member 11960509 Ответов: 0

Шифрование/дешифрование с использованием RSA c#.net


Всем Привет

Я сгенерировал пару открытый-закрытый ключ(RSA 4096 бит) с помощью puttygen, и я использую этот ключ в своем C#.net код. В основном идея создания этих ключей заключается в том, чтобы дать открытый ключ клиенту, и он зашифрует файл с помощью этого открытого ключа и поместит этот файл на защищенный сервер, а мы загрузим его через SFTP и расшифруем.
Теперь, когда клиент еще не готов, для моей цели кодирования я решил сам зашифровать тестовый файл с помощью открытого ключа, и мне это удалось.
Теперь, когда я использую этот зашифрованный файл и закрытый ключ, он говорит, что ключа не существует.
Я не могу продолжать дальше, и это действительно срочно.
Я впервые работаю с шифрованием/дешифрованием.
Любая помощь будет оценена по достоинству.

public  static void Encrypt(string publicKeyFileName, string plainFileName, string encryptedFileName)

        {

            // Variables

            CspParameters cspParams = null;

            RSACryptoServiceProvider rsaProvider = null;

            StreamReader publicKeyFile = null;

            StreamReader plainFile = null;

            FileStream encryptedFile = null;

            string publicKeyText = "";

            string plainText = "";

            byte[] plainBytes = null;

            byte[] encryptedBytes = null;

            try

            {

                // Select target CSP

                cspParams = new CspParameters();

                cspParams.ProviderType = 1; // PROV_RSA_FULL

                //cspParams.ProviderName; // CSP name

                rsaProvider = new RSACryptoServiceProvider(cspParams);

                // Read public key from file

                publicKeyFile = File.OpenText(publicKeyFileName);

                publicKeyText = publicKeyFile.ReadToEnd();

                // Import public key

                rsaProvider.FromXmlString(publicKeyText);

                // Read plain text from file

                plainFile = File.OpenText(plainFileName);

                plainText = plainFile.ReadToEnd();

                // Encrypt plain text

                plainBytes = Encoding.Unicode.GetBytes(plainText);

                encryptedBytes = rsaProvider.Encrypt(plainBytes, false);

                // Write encrypted text to file

                encryptedFile = File.Create(encryptedFileName);

                encryptedFile.Write(encryptedBytes, 0, encryptedBytes.Length);

            }

            catch (Exception ex)

            {

                // Any errors? Show them

                //Console.WriteLine("Exception encrypting file! More info:");

                //Console.WriteLine(ex.Message);

            }

            finally

            {

                // Do some clean up if needed

                if (publicKeyFile != null)

                {

                    publicKeyFile.Close();

                }

                if (plainFile != null)

                {

                    plainFile.Close();

                }

                if (encryptedFile != null)

                {

                    encryptedFile.Close();

                }

            }

        } // Encrypt


public   static void Decrypt(string privateKeyFileName, string encryptedFileName, string plainFileName)

        {

            // Variables

            CspParameters cspParams = null;

            RSACryptoServiceProvider rsaProvider = null;

            StreamReader privateKeyFile = null;

            FileStream encryptedFile = null;

            StreamWriter plainFile = null;

            string privateKeyText = "";

            string plainText = "";

            byte[] encryptedBytes = null;

            byte[] plainBytes = null;

            try

            {

                // Select target CSP

                cspParams = new CspParameters();

                cspParams.ProviderType = 1; // PROV_RSA_FULL

                //cspParams.ProviderName; // CSP name

                rsaProvider = new RSACryptoServiceProvider(cspParams);

                // Read private/public key pair from file

                privateKeyFile = File.OpenText(privateKeyFileName);

                privateKeyText = privateKeyFile.ReadToEnd();

                // Import private/public key pair

                rsaProvider.FromXmlString(privateKeyText);

                // Read encrypted text from file

                encryptedFile = File.OpenRead(encryptedFileName);

                encryptedBytes = new byte[encryptedFile.Length];

                encryptedFile.Read(encryptedBytes, 0, (int)encryptedFile.Length);

                // Decrypt text

                plainBytes = rsaProvider.Decrypt(encryptedBytes, false);

                // Write decrypted text to file

                plainFile = File.CreateText(plainFileName);

                plainText = Encoding.Unicode.GetString(plainBytes);

                plainFile.Write(plainText);

            }

            catch (Exception ex)

            {

                // Any errors? Show them

                //Console.WriteLine("Exception decrypting file! More info:");

                //Console.WriteLine(ex.Message);

            }

            finally

            {

                // Do some clean up if needed

                if (privateKeyFile != null)

                {

                    privateKeyFile.Close();

                }

                if (encryptedFile != null)

                {

                    encryptedFile.Close();

                }

                if (plainFile != null)

                {

                    plainFile.Close();

                }

            }

        } // Decrypt

    }

}



Я ПОЛУЧАЮ ОШИБКУ РЯДОМ
plainBytes = rsaProvider.Decrypt(encryptedBytes, false);





Спасибо!

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

Я попытался восстановить ключи и попытался зашифровать расшифровку с помощью различных программ, и я вижу ту же ошибку.

OriginalGriff

Не видя кода, который вы используете для шифрования и дешифрования, мы действительно ничего не можем сделать, чтобы помочь: мы понятия не имеем, что вы делаете, поэтому мы еще меньше знаем, что вы делаете неправильно!
Попробуйте опубликовать соответствующие фрагменты кода, и, возможно, это поможет.
Используйте виджет" улучшить вопрос", чтобы отредактировать свой вопрос и предоставить более подробную информацию.

Member 11960509

Спасибо, я обновил свой вопрос

0 Ответов