예제 #1
0
        public void EncryptDecryptTest()
        {
            var testData = Enumerable.Range(1, 3)
                           .SelectMany(i => Enumerable.Range(i, 65536))
                           .Select(x => (byte)x)
                           .ToArray();

            var expected = testData.ToArray();

            var password = "******";

            var encStream = new MemoryStream();
            var encRes    = EasyEncrypt.Encrypt(testData.ToStream(), encStream, password);

            Assert.True(encRes);
            var enc = encStream.ToArray();

            var decStream = new MemoryStream();
            var decRes    = EasyEncrypt.Decrypt(enc.ToStream(), decStream, password);

            Assert.True(decRes);
            var dec = decStream.ToArray();

            CollectionAssert.AreEqual(expected, dec);
        }
예제 #2
0
        public async Task <IHttpActionResult> GetWeb_Usuario(long id)
        {
            object[] web_Usuario;
            var      encrypter = new EasyEncrypt();
            //extraigo por cookie el rol del usuario
            var  c1  = ControllerContext.Request.Headers.GetCookies("fkrol").First();
            long rol = long.Parse(c1["fkrol"].Value);

            web_Usuario = db.SP_GetAllInfoUsers().Where(w => w.id_rol.Equals(rol) && w.usuario_id.Equals(id)).ToArray();

            //si el retorno del usuario llega en cero busca si es un usario de otro rol
            if (web_Usuario.Count() == 0)
            {
                web_Usuario = await db.Web_Administrador.Where(a => a.administrador_id == id && a.FK_web_administrador_rol.Equals(rol)).Select(a => new {
                    id          = a.administrador_id,
                    nombres     = a.nombres,
                    apellidos   = a.apellidos,
                    descripcion = a.descripcion,
                    correo      = a.correo,
                    extencion   = a.extension,
                    imagen      = a.imagen,
                    id_rol      = a.FK_web_administrador_rol
                }).ToArrayAsync();

                //await db.SaveChangesAsync();
            }

            else if (web_Usuario == null)
            {
                return(NotFound());
            }

            return(Ok(web_Usuario));
        }
예제 #3
0
        static void Main(string[] args)
        {
            /*                 Readme examples            */

            // Create encrypter with default algorithm (AES) and generate a new random key
            var encrypter = new EasyEncrypt();

            // Encrypt and decrypt a string
            var encryptedString = encrypter.Encrypt("Example data");
            var decryptedString = encrypter.Decrypt(encryptedString);

            /*                 AES encryption            */

            // Get key from encrypter
            byte[] key = encrypter.GetKey();

            // Create encrypter with default algorithm (AES) and use an existing key
            using var encrypterWithKey = new EasyEncrypt(key: key);

            // Create encrypter with default algorithm (AES) and create encryption key from password and salt (with PBKDF2)
            using var encrypterWithPassword = new EasyEncrypt("Password", "Salt12345678");

            // Encrypt and decrypt a byte[]
            var encryptedArray = encrypter.Encrypt(Encoding.UTF8.GetBytes("Example data"));
            var decryptedArray = encrypter.Decrypt(encryptedArray);

            /*                 Custom algorithms encryption            */

            // Create encrypter with DES encryption
            using var DESencrypter = new EasyEncrypt(DES.Create());

            // Create encryptor with TripleDES encryption and create encryption key from password and salt (with PBKDF2)
            using var tripleDeSencrypter = new EasyEncrypt("Password", "Salt12345678", TripleDES.Create());

            /*                Encrypting streams            */

            // Readable input stream, gets disposed when encrypted
            using var inputStream = new MemoryStream(Encoding.UTF8.GetBytes("Example data"));
            // Writable output stream, encrypted data gets written to this stream
            using var encryptedStream = new MemoryStream();
            // Encrypt our stream
            encrypter.EncryptStream(inputStream, encryptedStream);

            // Writable output stream, decrypted data gets written to this stream
            using var decryptedStream = new MemoryStream();
            // Decrypt our stream, encrypted data gets disposed
            encrypter.DecryptStream(encryptedStream, decryptedStream);

            /*            Encrypting files        */
            const string inputFile     = "Data.txt",
                         encryptedFile = "EncryptedData.txt",
                         decryptedFile = "DecryptedData.txt";

            // Encrypt a file, encrypted file gets created with encrypted data
            encrypter.EncryptFile(inputFile, encryptedFile);
            // Decrypt a file, decrypted file gets created with decrypted data
            encrypter.DecryptFile(encryptedFile, decryptedFile);
        }
예제 #4
0
        public void TestGenerateKey()
        {
            var key  = EasyEncrypt.CreateKey("password", "test12345678", 256);
            var key2 = EasyEncrypt.CreateKey("password2", "test12345678", 256);

            Console.WriteLine(Convert.ToBase64String(key));
            Assert.AreEqual("criGtQT7ZrS7SoRMvaXK4yuRm0XtTUJA7937nIzXa9Q=", Convert.ToBase64String(key));
            Assert.AreNotEqual("criGtQT7ZrS7SoRMvaXK4yuRm0XtTUJA7937nIzXa9Q=", Convert.ToBase64String(key2));
        }
예제 #5
0
        public void TestEncryptionAndDecryption()
        {
            var encryption = new EasyEncrypt();

            var testData  = "testData";
            var encrypted = encryption.Encrypt(testData);
            var decrypted = encryption.Decrypt(encrypted);

            Assert.AreEqual(testData, decrypted);
        }
예제 #6
0
        public void TestGenerateKeyConstructor()
        {
            var encryption = new EasyEncrypt("password", "salt12345678");

            var testData  = "testData";
            var encrypted = encryption.Encrypt(testData);
            var decrypted = encryption.Decrypt(encrypted);

            Assert.AreEqual(32, encryption.GetKey().Length);
            Assert.AreEqual(testData, decrypted);
        }
예제 #7
0
        public void TestEncryptDecrypt()
        {
            using var encrypter = new EasyEncrypt();

            string data      = "fasfeaw12fewavgffewa4rvar31242`343e12123`";
            string encrypted = encrypter.Encrypt(data);
            string decrypted = encrypter.Decrypt(encrypted);

            Assert.AreEqual(data, decrypted);
            Assert.AreNotEqual(data, encrypted);
        }
예제 #8
0
        public void TestEncryptingAndDecryptingMessage()
        {
            var encryption = new EasyEncrypt();

            var testData         = "testData";
            var message          = EasyTcpPacket.To <Message>(Encoding.UTF8.GetBytes(testData));
            var encryptedMessage = EasyTcpPacket.To <Message>(message.Data).Encrypt(encryption);
            var decryptedMessage = EasyTcpPacket.To <Message>(encryptedMessage.Data).Decrypt(encryption);

            Assert.AreEqual(message.ToString(), decryptedMessage.ToString());
            Assert.AreNotEqual(message.ToString(), encryptedMessage.ToString());
        }
예제 #9
0
        public void TestStreams()
        {
            using var encryptor = new EasyEncrypt();

            using var input = new MemoryStream(Encoding.UTF8.GetBytes("test"));
            var encrypted = new MemoryStream();
            var decrypted = new MemoryStream();

            encryptor.EncryptStream(input, encrypted);
            encryptor.DecryptStream(new MemoryStream(encrypted.ToArray()), decrypted);

            Assert.IsTrue(input.ToArray().SequenceEqual(decrypted.ToArray()));
        }
예제 #10
0
        public static void Run()
        {
            // Create new instance of EasyEncrypt with a key
            var encrypter = new EasyEncrypt(Aes.Create(), _encrypter.GetKey());

            // Create new server with encryption
            using var server = new EasyTcpServer().UseServerEncryption(encrypter).Start(Port);

            server.OnDataReceive += (sender, message) =>
            {
                Console.WriteLine(message.ToString()); // Message is automatically decrypted
            };
        }
예제 #11
0
        public void TestEncryptDecrypt()
        {
            using var encrypter = new EasyEncrypt();
            encrypter.EncryptFile("Data.txt", "Encrypted.txt");
            encrypter.DecryptFile("Encrypted.txt", "Decrypted.txt");

            string data      = File.ReadAllText("Data.txt"),
                   encrypted = File.ReadAllText("Encrypted.txt"),
                   decrypted = File.ReadAllText("Decrypted.txt");

            Assert.AreEqual(data, decrypted);
            Assert.AreNotEqual(data, encrypted);
        }
예제 #12
0
        public static async Task <Result <AggregateException> > Deprocess(Stream input, Stream output, string password)
        {
            var comp = new LzmaCompressor();

            var pipe = new Pipe(
                (i, o) => EasyEncrypt.Decrypt(i, o, password),
                (i, o) => comp.Decompress(i, o)
                );

            pipe.SetInput(input);
            pipe.SetOutput(output);
            pipe.BufferSize = 1024 * 1024;

            return(await pipe.Execute());
        }
예제 #13
0
        public static void Run()
        {
            const ushort PORT = 100;

            using var encrypter   = new EasyEncrypt("Password", "SALT1415312");
            using var server      = new EasyTcpServer().Start(PORT);
            server.OnDataReceive += (sender, message) =>
                                    Console.WriteLine($"Received: {message.Decrypt(encrypter).ToString()}");

            using var client = new EasyTcpClient();
            if (!client.Connect(IPAddress.Loopback, PORT))
            {
                return;
            }
            client.Send(EasyTcpPacket.To <Message>("Hello Server!").Encrypt(encrypter));
        }
예제 #14
0
        public static string AesDecrypt(this string encryptedInput)
        {
            try
            {
                var aes    = new EasyEncrypt(Password, Salt, Aes.Create());
                var result = aes.Decrypt(encryptedInput);
                aes.Dispose();

                return(result);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error AES Decrypt");
                return(null);
            }
        }
예제 #15
0
        public static void Connect()
        {
            var client = new EasyTcpClient();

            if (!client.Connect(IPAddress.Loopback, Port))
            {
                return;
            }

            using var encrypter = new EasyEncrypt("Key", Salt);

            // Send encrypted message
            // .Encrypt works on all EasyTcpPackets
            client.Send(EasyTcpPacket.To <Message>("TestMessage").Encrypt(encrypter)
                        .Compress()); // Compression also works on all EasyTcpPackets
        }
예제 #16
0
        private const string Salt = "Salt12345678"; // Random salt for each session is recommend if possible

        public static void Start()
        {
            // Create new encryptor instance
            // Default algorithm used is Aes
            // See EasyEncrypt class for more information
            var encrypter = new EasyEncrypt("Key", Salt);

            var server = new EasyTcpServer().Start(Port);

            server.OnDataReceive += (sender, message) =>
            {
                Console.WriteLine(message.Decompress() // Decompress package if compressed
                                  .Decrypt(encrypter)  // Decrypt message
                                  .ToString());
            };
        }
예제 #17
0
        public void TestEncryption()
        {
            ushort port = TestHelper.GetPort();

            using var encrypter = new EasyEncrypt();

            using var server      = new EasyTcpServer().UseServerEncryption(encrypter).Start(port);
            server.OnDataReceive += (sender, message) =>
            {
                Console.WriteLine(message);
                message.Client.Send(message);
            };
            using var client = new EasyTcpClient().UseClientEncryption(encrypter);

            Assert.IsTrue(client.Connect(IPAddress.Any, port));
            Assert.AreEqual("Test", client.SendAndGetReply("Test").ToString());
        }
예제 #18
0
        public void SendEncryptedData()
        {
            ushort port = TestHelper.GetPort();

            using var server      = new EasyTcpServer().Start(port);
            server.OnDataReceive += (sender, message) => message.Client.Send(message);

            var encryption = new EasyEncrypt();

            using var client = new EasyTcpClient();
            Assert.IsTrue(client.Connect(IPAddress.Any, port));

            string data = "123";
            var    m    = client.SendAndGetReply(EasyTcpPacket.To <Message>(data).Encrypt(encryption).Compress());

            Assert.AreEqual(data, m.Decompress().Decrypt(encryption).ToString());
        }
예제 #19
0
        public static void Connect()
        {
            /* Create new instance of EasyEncrypt with a password and (hardcoded) salt
             * Default algorithm is Aes
             */
            _encrypter = new EasyEncrypt("Password", "Salt2135321");

            // Create new client with encryption
            var client = new EasyTcpClient().UseClientEncryption(_encrypter);

            client.Connect("127.0.0.1", Port);

            // All data is now encrypted before sending
            client.Send("Data");

            // Encrypter gets disposed with client + protocol
            client.Dispose();
        }
예제 #20
0
        public void TestEncryptionFail()
        {
            ushort port = TestHelper.GetPort();

            using var encrypter = new EasyEncrypt();

            using var server = new EasyTcpServer().Start(port);
            int isEncrypted = 0;

            server.OnDataReceive += (sender, message) =>
            {
                if (message.ToString() != "Test")
                {
                    Interlocked.Increment(ref isEncrypted);
                }
                Console.WriteLine(message);
                message.Client.Send(message);
            };
            using var client = new EasyTcpClient().UseClientEncryption(encrypter);

            Assert.IsTrue(client.Connect(IPAddress.Any, port));
            Assert.AreEqual("Test", client.SendAndGetReply("Test").ToString());
            Assert.AreEqual(1, isEncrypted);
        }
예제 #21
0
 /// <summary></summary>
 /// <param name="encrypter"></param>
 public EncryptedPrefixLengthProtocol(EasyEncrypt encrypter)
 => Encrypter = encrypter;
예제 #22
0
        public async Task <ActionResult> ViewPartialLogin(LoginViewModel model)
        {
            //Valido los campos del modelo
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            //Valido el capcha
            if (!this.IsCaptchaValid("Captcha is not valid"))
            {
                ModelState.AddModelError(string.Empty, "Error: captcha no es válido.");
            }
            //si el captcha es valido
            else
            {
                try
                {
                    //Ejecuto los valores
                    var response = db.SP_Ingreso_Usuario(model.Usuario, model.Password).FirstOrDefault();
                    //
                    //await db.SaveChangesAsync();
                    //
                    if (response != null && response.codigo.Equals(200))
                    {
                        var encrypter = new EasyEncrypt();
                        var obj       = db.Web_Usuario.Where(u => u.Prestador.codigo.Equals(model.Usuario)).FirstOrDefault();

                        /**/
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                            1,
                            obj.usuario_id.ToString(),
                            DateTime.Now,
                            DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                            false,
                            obj.FK_usuario_rol.ToString()
                            );

                        String     Encrypt = FormsAuthentication.Encrypt(ticket);
                        HttpCookie cookie  = new HttpCookie("TIKECTCOOKIE", Encrypt);

                        //Pongo en cookie el rol del usuario para traer los datos del tablero de control
                        HttpCookie cookierol = new HttpCookie("fkrol", obj.FK_usuario_rol.ToString());

                        //
                        cookie.Expires    = DateTime.Now.AddMinutes((int)FormsAuthentication.Timeout.TotalMinutes);
                        cookierol.Expires = DateTime.Now.AddMinutes((int)FormsAuthentication.Timeout.TotalMinutes);

                        Response.Cookies.Add(cookierol);
                        Response.Cookies.Add(cookie);
                        /**/

                        return(RedirectToAction("Index", "Tablero"));
                    }
                    else if (response.codigo != 200)
                    {
                        ModelState.AddModelError(string.Empty, response.mensaje);

                        if (response.codigo == 1004)
                        {
                            var intento = db.Web_Usuario.Where(u => u.Prestador.codigo.Equals(model.Usuario)).Select(s => s.intentos_error_contrase).FirstOrDefault();
                            ModelState.AddModelError(string.Empty, string.Format("ha hecho {0} intentos de contraseña incorrecta", intento));

                            ViewBag.countPass = 1;
                        }
                    }
                    else
                    {
                        //Limpio campos
                        ModelState.Clear();
                        //envio un mensaje al usuario
                        ModelState.AddModelError(string.Empty, "La plataforma no esta respondiendo a su solicitud, por favor intente mas tarde.");
                    }
                }
                catch (Exception e)
                {
                    //envio error a la api logs errores
                    //y envio a la carpeta logs
                    APIS.LogsController log = new APIS.LogsController(e.ToString());
                    log.createFolder();
                    //Limpio campos
                    ModelState.Clear();
                    //envio error mensaje al usuario
                    ModelState.AddModelError(string.Empty, "Estamos presentando dificultades en el momento por favor intente mas tarde. ");
                    //ModelState.AddModelError(string.Empty, "Estamos"+e.ToString());
                }
            }//fin else captcha

            //retorno la vista en caso de que no se efectue el regsitro
            return(View("Index", model));
        }
예제 #23
0
 /// <summary>
 /// Shortcut for enabling encryption
 /// </summary>
 /// <param name="client"></param>
 /// <param name="encrypt"></param>
 public static T UseClientEncryption <T>(this T client, EasyEncrypt encrypt) where T : EasyTcpClient
 {
     client.Protocol = new EncryptedPrefixLengthProtocol(encrypt);
     return(client);
 }
예제 #24
0
 /// <summary>
 /// Decrypt message with EasyEncrypt
 /// </summary>
 /// <param name="data"></param>
 /// <param name="encryption">instance of easyEncrypt class</param>
 /// <returns>decrypted data</returns>
 public static T Decrypt <T>(this T data, EasyEncrypt encryption) where T : IEasyTcpPacket
 {
     data.Data = encryption.Decrypt(data.Data);
     return(data);
 }
예제 #25
0
        public void Start()
        {
            /* Prefix length protocol, (Default when not specified)
             * prefixes all data with its length. Length is a ushort as byte[2]
             * Max data size is 65.535 bytes. See LargeArray or streams examples for large data
             *
             * Example message:
             *     data: "data"
             *     length: 4 bytes
             *
             *     message: (ushort as byte[2]) 4 + "data"
             */
            using var defaultProtocol = new PrefixLengthProtocol();

            /* Delimiter protocol,
             * determines the end of a message based on a sequence of bytes
             *
             * Example message:
             *     data: "data"
             *     delimiter: "\r\n"
             *
             *     message: "data" + "\r\n"
             */
            bool autoAddDelimiter    = true; // Determines whether to automatically add the delimiter to the end of a message before sending
            bool autoRemoveDelimiter = true; // Determines whether to automatically remove the delimiter when triggering the OnDataReceive event

            using var delimiterProtocol = new DelimiterProtocol("\r\n", autoAddDelimiter, autoRemoveDelimiter);

            /* None protocol,
             * doesn't determine the end of a message
             * Reads all available bytes into 1 byte[]
             * Doesn't work with ReceiveStream/ReceiveLargeArray
             *
             * Example message:
             *     data: "data"
             *     message: "data"
             */
            int bufferSize  = 1024; // Max data(chunk) size
            var nonProtocol = new NoneProtocol(bufferSize);

            // Create client that uses a specific protocol
            using var client = new EasyTcpClient(nonProtocol);

            // Create a server that uses a specific protocol
            using var server = new EasyTcpServer(nonProtocol).Start(Port);

            /*             EasyTcp.Encryption
             *
             * Every protocol above is available with ssl
             * PrefixLengthSslProtocol, DelimiterSslProtocol & NoneSslProtocol
             * All ssl protocols have some extra parameters
             */

            // Client ssl protocol
            using var defaultClientSslProtocol = new PrefixLengthSslProtocol("localhost", acceptInvalidCertificates: false);

            // Server ssl protocol
            using var certificate = new X509Certificate2("certificate.pfx", "password");
            using var defaultServerSslProtocol = new PrefixLengthSslProtocol(certificate);

            /* The helper method client/server.UseSsl() as seen in Encryption.SslExample uses PrefixLengthSslProtocol
             * Use constructor with custom ssl protocol for DelimiterSslProtocol & NoneSslProtocol
             *
             *
             * EncryptedPrefixLengthProtocol,
             * this protocol encrypts all data with EasyEncrypt
             * See Encryption/CustomAlgorithmProtocol for more info
             * There is no Delimiter/None protocol for encryption with EasyEncrypt
             */

            var encrypter = new EasyEncrypt();

            using var encryptedPrefixLengthProtocol = new EncryptedPrefixLengthProtocol(encrypter);
        }
예제 #26
0
 /// <summary>
 /// Shortcut for enabling encryption
 /// </summary>
 /// <param name="server"></param>
 /// <param name="encrypt"></param>
 public static T UseServerEncryption <T>(this T server, EasyEncrypt encrypt) where T : EasyTcpServer
 {
     server.Protocol = new EncryptedPrefixLengthProtocol(encrypt);
     return(server);
 }