Пример #1
0
        public string DESdecrypt(string emri, string keystr, string ivstr, string teksti)
        {
            rsa    rsa    = new rsa();
            string filere = File.ReadAllText("C:/Users/hp/Desktop/keys/users.txt");

            string[] a = filere.Split();
            for (int i = 0; i < a.Length; i++)
            {
                if (emri == a[i])
                {
                    emri = a[i - 1];
                }
            }

            string k = rsa.RSAdecr(emri, keystr);

            byte[] key        = Convert.FromBase64String(k);
            byte[] iv         = Convert.FromBase64String(ivstr);
            byte[] tekstibyte = Encoding.UTF8.GetBytes(teksti);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream             memoryStream   = new MemoryStream
                                                          (Convert.FromBase64String(teksti));
            CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                         cryptoProvider.CreateDecryptor(key, iv), CryptoStreamMode.Read);
            StreamReader reader = new StreamReader(cryptoStream);

            return(reader.ReadToEnd());
        }
Пример #2
0
        public string DESenc(string emri, string keystr, string ivstr, string teksti)
        {
            rsa    rsa = new rsa();
            string k   = rsa.RSAdecr(emri, keystr);

            byte[] key        = Convert.FromBase64String(k);
            byte[] iv         = Convert.FromBase64String(ivstr);
            byte[] tekstibyte = Encoding.UTF8.GetBytes(teksti);

            if (String.IsNullOrEmpty(teksti))
            {
                throw new ArgumentNullException
                          ("The string which needs to be encrypted can not be null.");
            }
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream             memoryStream   = new MemoryStream();
            CryptoStream             cryptoStream   = new CryptoStream(memoryStream,
                                                                       cryptoProvider.CreateEncryptor(key, iv), CryptoStreamMode.Write);
            StreamWriter writer = new StreamWriter(cryptoStream);

            writer.Write(teksti);
            writer.Flush();
            cryptoStream.FlushFinalBlock();
            writer.Flush();
            return(Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
        }
Пример #3
0
        static void Main(string[] args)
        {
            rsa cifrado = new rsa();

            Console.WriteLine("Ingrese p");
            int a = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Ingrese q");
            int b = Convert.ToInt32(Console.ReadLine());

            cifrado.generarLlaves(a, b);
            Console.WriteLine("Texto");
            string texto = Console.ReadLine();

            Console.WriteLine("Llave");
            string llave = Console.ReadLine();

            Console.WriteLine("Nombre");
            string nombre = Console.ReadLine();

            cifrado.Cifrar(texto, llave, nombre);
            Console.WriteLine("Descifrar texto");
            string des = Console.ReadLine();

            Console.WriteLine("Llave para descifrar");
            string llave2 = Console.ReadLine();

            Console.WriteLine("Nombre para descifrar");
            string nombre2 = Console.ReadLine();

            cifrado.Descifrar(des, llave2, nombre2);
        }
Пример #4
0
        public broker()
        {
            name  = "Default Broker";
            clist = new List <bcertificate>();

            rsa brsa = new rsa();

            bpvk = brsa.getPrivate();
            bpbk = brsa.getPublic();
        }
Пример #5
0
        private void genRSAKeys(out BigInteger e, out BigInteger d, out BigInteger n)
        {
            rsa Rsa = new rsa();

            e = new BigInteger(Rsa.gete());
            //Console.WriteLine("\nprivate KEY(V): " + e);
            d = new BigInteger(Rsa.getd());
            //Console.WriteLine("\nPRIVATE KEY(U): " + d);
            n    = new BigInteger(Rsa.getn());
            nrsa = n;
        }
Пример #6
0
        public user(string n, string m, string c)
        {
            name     = n;
            mail     = m;
            card     = c;
            commited = false;

            rsa ursa = new rsa();

            upvk = ursa.getPrivate();
            upbk = ursa.getPublic();
        }
Пример #7
0
        public user()
        {
            name     = "defaultname";
            mail     = "defaultmail";
            card     = "defaultcard";
            commited = false;

            rsa ursa = new rsa();

            upvk = ursa.getPrivate();
            upbk = ursa.getPublic();
        }
Пример #8
0
        private void button2_Click(object sender, EventArgs e)
        {
            string username = textBox1.Text;
                string password = textBox2.Text;
            if (username.Equals("") || password.Equals("")) {
                MessageBox.Show("用户名密码不能为空","提示");
                }
                 else
                {
                char[] cc = password.ToCharArray();

                string sendpsd = "";
                rsa myrsa = new rsa();
                for (int i = 0; i < cc.Length; i++)
                {
                    sendpsd += myrsa.rsamain(cc[i], 0);
                    sendpsd += "#";
                }

                client tcpclient = new client();
                tcpclient.SendMessage(username, sendpsd);
            }
        }
Пример #9
0
    public void readText(string mesazhi, string token)
    {   
        faza3 f3=new faza3();
        if (String.IsNullOrEmpty(token))
        {
            string[] msg = mesazhi.Split();
            string m = msg[0] + " " + msg[1] + " " + msg[2] + " " + msg[3];
            //string t = Console.ReadLine();//File.ReadAllText("C:/Users/hp/Desktop/keys/"+ emri +"encrypted.xml");
            string dec = decrypt(m);
            string[] arg = dec.Split();
        
    



        Console.WriteLine(" Emri ..:" + arg[0]);
        Console.WriteLine(" Decrypted ..:" + arg[1]);
           
        }
        else
        {
            string[] msg = mesazhi.Split();
            rsa rsa = new rsa();

             string m = msg[0] + " " + msg[1] + " " + msg[2] + " " + msg[3];
             string dec = decrypt(m);
             string[] arg = dec.Split();
             string filere = File.ReadAllText("C:/Users/hp/Desktop/keys/users.txt");//
             string[] a = filere.Split();
             string h = "";
            
            if(f3.status(token)=="Nuk ekziston")
                {
                    Console.Write(" Tokeni jo valid ");
                    return;
                }
                
            
            string[] tokenich = token.Split();
            string derguesi = "";
            for (int i = 0; i < a.Length; i++)
                {
                    if (tokenich[0] == a[i]) { derguesi = a[i - 1]; }
                }
            string k = rsa.RSAdecr(derguesi, msg[4]);
            string s = m + " " + k;
            string desdcr = decrypt(s);
            string[] dcr = desdcr.Split();
            
             Console.WriteLine(" Emri i marresit ..:" + arg[0]);
             Console.WriteLine(" Decrypted ..:" + arg[1]);
             Console.WriteLine(" Emri i derguesit ..:" + derguesi);//Encoding.ASCII.GetString(Convert.FromBase64String(derguesi)));
               if (arg[1] == dcr[1])
                {
                    Console.WriteLine(" Nenshkrimi ..: valid");
                }
            else
                {
                    Console.WriteLine(" Nenshkrimi ..: jovalid , mungon celesi publik" + derguesi);
                }


        File.WriteAllText("C:/Users/hp/Desktop/keys/" + arg[0] + "decrypted.xml", dec);
        Console.WriteLine("teksti u ruajt ne ...:" + "C:/Users/hp/Desktop/keys/");

    }
Пример #10
0
        public async Task <ActionResult> Post([FromRoute] string name, [FromForm] IFormFile archivo, [FromForm] IFormFile llave)
        {
            /*Crear Carpeta 'Uploads' para guardar los archivos subidos*/

            string workingDirectory   = Environment.CurrentDirectory;
            string pathFolderActual   = Directory.GetParent(workingDirectory).FullName;
            string pathFilesDirectory = pathFolderActual + "\\Uploads\\";

            string rutaArchivo = pathFilesDirectory + archivo.FileName;
            string rutaLlave   = pathFilesDirectory + llave.FileName;

            string extensionArchivo = "." + archivo.FileName.Split(".")[1];

            // Ser verifica si existe el directorio y se elimina para evitar duplicidad
            if (Directory.Exists(pathFilesDirectory))
            {
                Directory.Delete(pathFilesDirectory, true);
            }

            Directory.CreateDirectory(pathFilesDirectory);

            using (var fileStream = new FileStream((rutaArchivo), FileMode.Create))
            {
                await archivo.CopyToAsync(fileStream);
            }

            using (var fileStream = new FileStream((rutaLlave), FileMode.Create))
            {
                await llave.CopyToAsync(fileStream);
            }


            string pathCifrados = pathFolderActual + "\\Cifrados\\";

            // Ser verifica si existe el directorio y se elimina para evitar duplicidad
            if (Directory.Exists(pathCifrados))
            {
                Directory.Delete(pathCifrados, true);
            }

            Directory.CreateDirectory(pathCifrados);

            FileStream files;

            switch (extensionArchivo)
            {
            case ".txt": {
                rsa cifradoRsa = new rsa();
                cifradoRsa.Cifrar(rutaArchivo, rutaLlave, name);
                var streamCompress = System.IO.File.OpenRead($"{name}.rsa");
                return(new FileStreamResult(streamCompress, "application/" + ".rsa")
                    {
                        FileDownloadName = name + ".rsa"
                    });
            }
            break;

            case ".rsa":
            {
                rsa descifradoRsa = new rsa();
                descifradoRsa.Descifrar(rutaArchivo, rutaLlave, name);
                var streamCompress = System.IO.File.OpenRead($"{name}.txt");
                return(new FileStreamResult(streamCompress, "application/" + ".txt")
                    {
                        FileDownloadName = name + ".txt"
                    });
            }
            break;

            default: {
                return(BadRequest());
            }
            break;
            }
        }
Пример #11
0
        public ActionResult generarLlaves([FromRoute] string p, [FromRoute] string q)
        {
            /*Crear Carpeta 'Keys' para guardar las llaves*/

            string workingDirectory  = Environment.CurrentDirectory;
            string pathFolderActual  = Directory.GetParent(workingDirectory).FullName;
            string pathDirectoryKeys = pathFolderActual + "\\Keys\\";

            string rutaKeyPublica = "";
            string rutaKeyPrivada = "";

            // Ser verifica si existe el directorio y se elimina para evitar duplicidad
            if (Directory.Exists(pathDirectoryKeys))
            {
                Directory.Delete(pathDirectoryKeys, true);
            }

            Directory.CreateDirectory(pathDirectoryKeys);



            try
            {
                rsa generarKeys = new rsa();
                // Se verifica si son primos
                if (generarKeys.esPrimo(int.Parse(p)) && generarKeys.esPrimo(int.Parse(q)))
                {
                    // Se verifican si estan entre 50 y 32000
                    if ((int.Parse(p) > 50 && int.Parse(p) < 32000) && (int.Parse(q) > 50 && int.Parse(q) < 32000))
                    {
                        generarKeys.generarLlaves(int.Parse(p), int.Parse(q));

                        //Escribir archivo para public key
                        rutaKeyPublica = pathDirectoryKeys + "public.key";
                        System.IO.File.WriteAllBytes(rutaKeyPublica, System.Text.Encoding.Default.GetBytes(generarKeys.public_key));

                        //Escribir archivo para private key
                        rutaKeyPrivada = pathDirectoryKeys + "private.key";
                        System.IO.File.WriteAllBytes(rutaKeyPrivada, System.Text.Encoding.Default.GetBytes(generarKeys.private_key));


                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddEntry("public.key", System.IO.File.ReadAllBytes(rutaKeyPublica));
                            zip.AddEntry("private.key", System.IO.File.ReadAllBytes(rutaKeyPrivada));

                            using (MemoryStream output = new MemoryStream())
                            {
                                zip.Save(output);
                                return(File(output.ToArray(), "application/zip", "Keys.zip"));
                            }
                        }
                    }
                    else
                    {
                        return(BadRequest());
                    }
                }
                else
                {
                    return(BadRequest());
                }
            }
            catch (Exception ex) {
                return(BadRequest());
            }
        }
Пример #12
0
        public void StartServer()
        {
            TcpListener myListener = null;
            try
            {
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                myListener = new TcpListener(localAddr, PORT);

                myListener.Start();
                Console.WriteLine("开始侦听 {0} 端口……", PORT);

                //开始阻塞
                while (true)
                {
                    Socket mySocket = myListener.AcceptSocket();

                    Console.WriteLine("接收到客户的连接");

                    Byte[] recvBytes = new Byte[256];
                    Int32 bytes = mySocket.Receive(recvBytes, recvBytes.Length, SocketFlags.None);

                    // 将缓冲区当中的 byte 数组,转化为 字符串.
                    String str = Encoding.ASCII.GetString(recvBytes, 0, bytes);

                    Console.WriteLine("接收到来自客户端的数据为:{0}", str);

                    string[] s = str.Split(new char[] { '#' });

                    string username = s[0];
                    string password = "";
                    int temp;
                    for (int i = 1; i < s.Length - 1; i++)
                    {
                        rsa myrsa = new rsa();
                        temp = Int32.Parse(s[i]);
                        password += (char)myrsa.rsamain(temp, 1);
                    }
                    //connect database
                    bool state = false;
                    state = sql.domysql(username, password);
                    if (state)
                    {
                        //登陆成功
                        Byte[] sendBytes = Encoding.ASCII.GetBytes("ok");
                        mySocket.Send(sendBytes, sendBytes.Length, SocketFlags.None);
                    }
                    else
                    {
                        //失败
                        Byte[] sendBytes = Encoding.ASCII.GetBytes("wrong");
                        mySocket.Send(sendBytes, sendBytes.Length, SocketFlags.None);
                    }
                    // 关闭 Socket
                    mySocket.Close();
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("SocketException: {0}", e);
            }
            finally
            {

                myListener.Stop();
            }
        }