Exemple #1
0
        public void HybridEncryption_FilePath()
        {
            var myPrivateKeyJson = @"
{
   ""PrivateKey"":""NquxhQX9cmWkyDulDIm6OEzty5roXQHApdJInL4gPQbmkXqrVBHhkA=="",
   ""PublicKey"":{
      ""Qx"":""tS37fNpfdy5diNusCoalxUn0HOdjqJk2OybUA9jy8HnzCSg0rFi3bA=="",
      ""Qy"":""sYIRXtP1j3tspMyJOeuCDdG4Ifm3DKC+yIHOFyLUTt8R4z0OxWpLqg==""
   },
   ""InculdePrivateKey"":true
}
";
            var myPrivateKey     = EcKeyPair.FromJson(myPrivateKeyJson);
            var bobPublicAns1Key = EcKeyPair.CreateFromAnsi(Convert.FromBase64String("BFEECnHOtY1L3He8vwsH0ahiDZZzavjxZzciXYXrzaNP1Zn/x1sL+4lvOpktdaZSjgWH/X2JI1rAqBVl7NO3R0UWJ4WtKnrGa5IhSiW0oC7s2lU="));

            File.WriteAllText(this.InputFile, "My Stuff");

            var encryptionParameter = new HybridEncryption.EncryptionParameter
            {
                PublicKeys = new[] { myPrivateKey.ExportPublicKey(), bobPublicAns1Key.ExportPublicKey() },
            };

            HybridEncryption.Encrypt(this.InputFile, this.EncryptedFile, encryptionParameter);

            var decryptionParameter = new HybridEncryption.DecryptionParameter
            {
                PrivateKey = myPrivateKey,
            };
            var info = HybridEncryption.Decrypt(this.EncryptedFile, this.PlainFile, decryptionParameter);

            Console.Out.WriteLine(info.FileName);
            Console.Out.WriteLine(File.ReadAllText(this.PlainFile));
        }
        public void Decrypt_Should_Throw_Crypto_Exception_If_Encrypted_Data_Was_Changed()
        {
            EncryptedPacket packet = ValidMessagePacket;

            packet.EncryptedData = new byte[256];

            Assert.That(() => { HybridEncryption.Decrypt(packet, asymmetricPublicKey); }, Throws.InstanceOf(typeof(CryptoException)));
        }
        public void Can_Recover_Encrypted_File()
        {
            byte[]          fileBytes       = Random.GetNumbers(2048);
            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            byte[] decryptedBytes = HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);

            CollectionAssert.AreEqual(fileBytes, decryptedBytes);
        }
Exemple #4
0
        public void Encrypt()
        {
            var data = "P@ssw0rd";

            var keys      = HybridEncryption.GenerateKeys();
            var encrypted = HybridEncryption.Encrypt(data, keys.PublicKey);
            var decrypted = HybridEncryption.Decrypt(encrypted, keys.KeysPair);

            Console.WriteLine(encrypted);
            Assert.AreEqual(data, decrypted);
        }
        public void Can_Recover_Encrypted_Message()
        {
            string inputString = "This is another test string";

            byte[]          messageBytes    = Encoding.UTF8.GetBytes(inputString);
            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.Message, messageBytes, asymmetricPublicKey);

            byte[] decryptedBytes   = HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);
            string decryptedMessage = Encoding.UTF8.GetString(decryptedBytes);

            Assert.AreEqual(inputString, decryptedMessage);
        }
        public void Decryption_Throws_CryptoException_When_Hmac_Differs()
        {
            byte[] fileBytes = Random.GetNumbers(2048);

            EncryptedPacket encryptedPacket = HybridEncryption.Encrypt(DataType.File, fileBytes, asymmetricPublicKey);

            encryptedPacket.Hmac[25] = (byte)((encryptedPacket.Hmac[25] + 1) % 255);

            Assert.Throws(typeof(CryptoException), () =>
            {
                HybridEncryption.Decrypt(encryptedPacket, asymmetricPublicKey);
            });
        }
Exemple #7
0
        public void EncryptAndDecrypt()
        {
            #region Arrange

            var alice = EllipticCurveCryptographer.CreateKeyPair(true);

            var encryptionParameter = new HybridEncryption.EncryptionParameter()
            {
                PublicKeys = new[] { alice.ExportPublicKey() },
            };

            var decryptionParameter = new HybridEncryption.DecryptionParameter()
            {
                PrivateKey = alice,
            };

            #endregion

            #region Act

            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, encryptionParameter);
                }

            using (var input = File.OpenRead(this.OutputFile))
                using (var output = File.Create(this.ResultFile))
                {
                    HybridEncryption.Decrypt(input, output, decryptionParameter);
                }

            #endregion

            #region Assert

            var inputData  = File.ReadAllBytes(this.InputFile);
            var outputData = File.ReadAllBytes(this.OutputFile);
            var resultData = File.ReadAllBytes(this.ResultFile);

            Assert.That(FileOperation.HasFileSignature(this.OutputFile), "HasFileSignature");
            Assert.That(inputData.Length, Is.LessThan(outputData.Length), "Input file is smaller than output file");
            Assert.That(outputData, Is.Not.EquivalentTo(resultData), "Encrypted file is not equal to plain file");
            Assert.That(inputData.Length, Is.EqualTo(resultData.Length), "size of plain file is equal to encrypted file");
            Assert.That(inputData, Is.EquivalentTo(resultData), "plain file is equal to encrypted file");

            #endregion
        }
Exemple #8
0
        public void EncryptAndDecryptMultipleKeys()
        {
            #region Arrange

            var ecKeyPairInfos      = Encryption.NitroKey.EllipticCurveCryptographer.GetEcKeyPairInfos().First();
            var encryptionParameter = new HybridEncryption.EncryptionParameter()
            {
                PublicKeys = new[] { ecKeyPairInfos.PublicKey.ExportPublicKey() }
            };
            var decrptionParameter = new HybridEncryption.DecryptionParameter
            {
                Password = Constants.TestPin
            };

            #endregion

            #region Act

            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, encryptionParameter);
                }

            using (var input = File.OpenRead(this.OutputFile))
                using (var output = File.Create(this.ResultFile))
                {
                    HybridEncryption.Decrypt(input, output, decrptionParameter);
                }

            #endregion

            #region Assert

            var inputData  = File.ReadAllBytes(this.InputFile);
            var outputData = File.ReadAllBytes(this.OutputFile);
            var resultData = File.ReadAllBytes(this.ResultFile);

            Assert.That(inputData.Length, Is.LessThan(outputData.Length), "Input file is smaller than output file");
            Assert.That(outputData, Is.Not.EquivalentTo(resultData), "Encrypted file is not equal to plain file");
            Assert.That(FileOperation.HasFileSignature(this.OutputFile), "HasFileSignature");
            Assert.That(inputData.Length, Is.EqualTo(resultData.Length), "size of plain file is equal to encrypted file");
            Assert.That(inputData, Is.EquivalentTo(resultData), "plain file is equal to encrypted file");

            #endregion
        }
Exemple #9
0
        static void Encrypt_Stream(int dataSize)
        {
            var data            = CryptoHelper.GenerateBytes(dataSize);
            var keys            = HybridEncryption.GenerateKeys();
            var encryptedStream = new MemoryStream();
            var decryptedStream = new MemoryStream();

            HybridEncryption.Encrypt(new MemoryStream(data), encryptedStream, keys.PublicKey);
            var encrypted = encryptedStream.ToArray();

            HybridEncryption.Decrypt(new MemoryStream(encrypted), decryptedStream, keys.KeysPair);
            var decrypted = decryptedStream.ToArray();

            if (dataSize <= 1024)
            {
                Console.WriteLine(Convert.ToBase64String(encrypted));
            }
            CollectionAssert.AreEqual(data, decrypted);
        }
Exemple #10
0
        public void EncryptAndDecryptWithFilename()
        {
            #region Arrange

            var alice = EllipticCurveCryptographer.CreateKeyPair(true);

            var encryptionParameter = new HybridEncryption.EncryptionParameter()
            {
                PublicKeys = new[] { alice.ExportPublicKey() },
                Filename   = Guid.NewGuid().ToString(),
            };

            var decryptionParameter = new HybridEncryption.DecryptionParameter()
            {
                PrivateKey = alice,
            };

            #endregion

            #region Act

            using (var input = File.OpenRead(this.InputFile))
                using (var output = File.Create(this.OutputFile))
                {
                    HybridEncryption.Encrypt(input, output, encryptionParameter);
                }

            DecryptInfo info;
            using (var input = File.OpenRead(this.OutputFile))
                using (var output = File.Create(this.ResultFile))
                {
                    info = HybridEncryption.Decrypt(input, output, decryptionParameter);
                }

            #endregion

            #region Assert

            Assert.That(encryptionParameter.Filename, Is.EqualTo(info.FileName), "is decrypted filename equal to input filename");

            #endregion
        }
        private async void DecryptCommandHandling()
        {
            var result = new PasswordWindow().ShowDialog();

            if (result == null || !(bool)result)
            {
                return;
            }

            this.IsBusy = true;

            var hsmPin = SimpleIoc.Default.GetInstance <PasswordViewModel>().Password;

            await Task.Run(() =>
            {
                DecryptInfo info;
                var targetPath = $"{this.FilePath}.dec";

                using (var input = File.OpenRead(this.FilePath))
                    using (var output = File.Create(targetPath))
                    {
                        info = HybridEncryption.Decrypt(input, output, new HybridEncryption.DecryptionParameter()
                        {
                            Progress   = this.ReportProgress,
                            IsCanceled = () => this.IsCanceled,
                            Password   = hsmPin,
                        });
                    }

                var decryptedFileName = Path.Combine(Path.GetDirectoryName(this.FilePath), info.FileName);
                if (File.Exists(decryptedFileName))
                {
                    var dto            = new DateTimeOffset(DateTime.Now);
                    decryptedFileName += $".{dto.ToUnixTimeMilliseconds()}{Path.GetExtension(info.FileName)}";
                }

                File.Move(targetPath, decryptedFileName);
            });

            this.IsBusy = false;
        }
        public void Decrypt_Should_Throw_Crypto_Exception_If_RSA_Public_Key_Is_Invalid()
        {
            asymmetricPublicKey.Modulus = new byte[1];

            Assert.That(() => { HybridEncryption.Decrypt(ValidMessagePacket, asymmetricPublicKey); }, Throws.InstanceOf(typeof(CryptoException)));
        }
        /// <summary>
        /// Add sent messages from list of packets
        /// </summary>
        /// <param name="sent"></param>
        /// <returns>Amount of packages which failed to be decrypted</returns>
        private async Task <int> AddSentMessages(IList <StrippedDownEncryptedPacket> sent)
        {
            // try to link messages to contacts
            BoxedInt    boxedInt = new BoxedInt();
            List <Task> tasks    = new List <Task>(sent.Count);

            foreach (StrippedDownEncryptedPacket packet in sentPackets)
            {
                // skip if current user is both the sender and receiver
                if (packet.Receiver.Id == packet.Sender.Id)
                {
                    continue;
                }

                tasks.Add(Task.Run(() =>
                {
                    // find receiver in contact list
                    ContactPerson receiver = contactList.FirstOrDefault(c => c.Id == packet.Receiver.Id);
                    if (receiver != null)
                    {
                        if (packet.DataType == DataType.Message)
                        {
                            try
                            {
                                string message = Encoding.UTF8.GetString(HybridEncryption.Decrypt(packet.EncryptedPacket, AsymmetricEncryption.PublicKey, true));

                                lock (receiver.LockObject)
                                {
                                    receiver.Messages.Add(new Message
                                    {
                                        SenderName        = Client.UserName,
                                        SendTime          = packet.SendDateTime,
                                        MessageFromSender = message,
                                        DataType          = packet.DataType,
                                        Packet            = packet,
                                    });
                                }
                            }
                            catch (CryptoException)
                            {
                                lock (boxedInt)
                                {
                                    boxedInt.Integer++;
                                }
                            }
                        }
                        else
                        {
                            lock (receiver.LockObject)
                            {
                                receiver.Messages.Add(new Message
                                {
                                    SenderName        = receiver.UserName,
                                    SendTime          = packet.SendDateTime,
                                    MessageFromSender = $"This is a {packet.DataType}",
                                    DataType          = packet.DataType,
                                    Packet            = packet
                                });
                            }
                        }
                    }
                }));
            }

            // wait for all to finish
            await Task.WhenAll(tasks);

            return(boxedInt.Integer);
        }
        /// <summary>
        /// Add received messages from list of packets
        /// </summary>
        /// <param name="received"></param>
        /// <returns>Amount of packages which failed to be decrypted</returns>
        private async Task <int> AddReceivedMessages(IList <StrippedDownEncryptedPacket> received)
        {
            // try to link messages to contacts
            BoxedInt    boxedInt = new BoxedInt();
            List <Task> tasks    = new List <Task>(received.Count);

            foreach (StrippedDownEncryptedPacket packet in received)
            {
                // find sender in contact list
                tasks.Add(Task.Run(() =>
                {
                    ContactPerson sender = contactList.FirstOrDefault(c => c.Id == packet.Sender.Id);
                    if (sender != null)
                    {
                        // ignore duplicates
                        if (sender.Messages.All(m => m.SendTime != packet.SendDateTime))
                        {
                            if (packet.DataType == DataType.Message)
                            {
                                try
                                {
                                    string message = Encoding.UTF8.GetString(HybridEncryption.Decrypt(packet.EncryptedPacket, AsymmetricEncryption.PublicKeyFromXml(sender.PublicKey)));

                                    // add new message to chat
                                    lock (sender.LockObject)
                                    {
                                        sender.Messages.Add(new Message
                                        {
                                            SenderName        = sender.UserName,
                                            SendTime          = packet.SendDateTime,
                                            MessageFromSender = message,
                                            DataType          = packet.DataType,
                                            Packet            = packet,
                                            Sender            = sender
                                        });
                                    }
                                }
                                catch (CryptoException)
                                {
                                    lock (boxedInt)
                                    {
                                        boxedInt.Integer++;
                                    }
                                }
                            }
                            else
                            {
                                lock (sender.LockObject)
                                {
                                    sender.Messages.Add(new Message
                                    {
                                        SenderName        = sender.UserName,
                                        SendTime          = packet.SendDateTime,
                                        MessageFromSender = $"This is a {packet.DataType}",
                                        DataType          = packet.DataType,
                                        Packet            = packet,
                                        Sender            = sender
                                    });
                                }
                            }
                        }
                    }
                }));
            }

            await Task.WhenAll(tasks);

            return(boxedInt.Integer);
        }