Member 14100501 Ответов: 1

Как реализовать алгоритм AES с помощью C#


Я должен отправить файл от пользователя а на сервер
Вот что мне здесь нужно:
1. от пользователя файл будет передан на сервер в зашифрованном виде
2. сервер получит файл, расшифрует и сохранит его.
3. Это действие следует выполнять с использованием асимметричного ключа шифрования концепции.
4. Целесообразно использование отдельных графических форм как для пользователя, так и сервера
Может ли кто - нибудь помочь мне реализовать это?

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;


namespace Authentication_Check
{
    class Program
    {
        static void Main(string[] args)
        {
            // Declaring Variables //
            string SourceData;
            byte[] tmpSource;
            byte[] tmpHash;


            // Enter any Text //
            Console.WriteLine("Enter any Tetx");
            SourceData = Console.ReadLine();

            //Create a byte array from Source data
            tmpSource = ASCIIEncoding.ASCII.GetBytes(SourceData);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine(" Key pair is generating....Please wait for while");
            Console.WriteLine();


            //RSA key pair Generator generates the RSA kay pair based on the Random Number and the strength of key required 
            RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            AsymmetricCipherKeyPair keyPair = rsaKeyPairGenerator.GenerateKeyPair();

            //Extracting the private key from the pair
            RsaKeyParameters privatekey = (RsaKeyParameters)keyPair.Private;
            RsaKeyParameters publickey = (RsaKeyParameters)keyPair.Public;

            //To print the public key in pem format
            TextWriter textWriter1 = new StringWriter();
            PemWriter pemWriter1 = new PemWriter(textWriter1);
            pemWriter1.WriteObject(publickey);
            pemWriter1.Writer.Flush();
            string print_publickey = textWriter1.ToString();
            Console.WriteLine("Public key is: {0}", print_publickey);
            Console.WriteLine();


            // Encryption Process
            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());
            cipher.Init(true, publickey);
            byte[] ciphertext = cipher.ProcessBlock(tmpSource, 0, tmpSource.Length);
            string result = Encoding.UTF8.GetString(ciphertext);
            Console.WriteLine("Encrypted text:");
            Console.WriteLine(result);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Do you want to decrypt the text? press 'Y' for yes and any other key key for no");
            char input = Console.ReadKey().KeyChar;

            if (input == 'Y' || input == 'y')
                Decryption(ciphertext, privatekey);
        }

        static void Decryption(byte[] ct, RsaKeyParameters pvtkey)
        {
            IAsymmetricBlockCipher Cipher1 = new OaepEncoding(new RsaEngine());
            Cipher1.Init(false, pvtkey);
            byte[] deciphered = Cipher1.ProcessBlock(ct, 0, ct.Length);
            string decipheredText = Encoding.UTF8.GetString(deciphered);
            Console.WriteLine();
            Console.WriteLine();

            Console.WriteLine("Decrypted Text:{0}", decipheredText);
            Console.WriteLine();
            Console.WriteLine();





        }





    }
}

1 Ответов

Рейтинг:
0

OriginalGriff

Мы не делаем домашнее задание: оно задано не просто так. Она существует для того, чтобы вы думали о том, что вам сказали, и пытались понять это. Он также существует для того, чтобы ваш наставник мог определить области, в которых вы слабы, и сосредоточить больше внимания на корректирующих действиях.

Попробуйте сами, возможно, вы обнаружите, что это не так сложно, как вы думаете!

Если вы столкнетесь с конкретной проблемой, то, пожалуйста, спросите об этом, и мы сделаем все возможное, чтобы помочь. Но мы не собираемся делать все это для вас!