Esempio n. 1
0
        public static void DecryptPacket(ServerState state, byte[] packet)
        {
            using (var reader = new Reader(packet))
            {
                var ID = reader.ReadUInt16();
                reader.Seek(3, SeekOrigin.Current);
                var Version = reader.ReadUInt16();

                byte[] cipherText = reader.ReadAllBytes, plainText;

                var Name = Packet_Names.GetName(ID);

                switch (ID)
                {
                case 10100:
                {
                    plainText = cipherText;

                    break;
                }

                case 10101:
                {
                    state.ClientKey = cipherText.Take(32).ToArray();

                    var nonce = GenericHash.Hash(state.ClientKey.Concat(state.ServerKey.PublicKey).ToArray(), null,
                                                 24);

                    cipherText = cipherText.Skip(32).ToArray();

                    plainText = PublicKeyBox.Open(cipherText, nonce, state.ServerKey.PrivateKey, state.ClientKey);

                    state.SessionKey        = plainText.Take(24).ToArray();
                    state.ClientState.Nonce = plainText.Skip(24).Take(24).ToArray();

                    plainText = plainText.Skip(24).Skip(24).ToArray();

                    break;
                }

                default:
                {
                    state.ClientState.Nonce = Utilities.Increment(Utilities.Increment(state.ClientState.Nonce));

                    plainText = SecretBox.Open(new byte[16].Concat(cipherText).ToArray(), state.ClientState.Nonce,
                                               state.SharedKey);

                    break;
                }
                }

                ClientCrypto.EncryptPacket(state.ClientState, ID, Version, plainText);

                Console.WriteLine(
                    $"[{DateTime.Now.ToLongTimeString()}, CLIENT, {ID}] {Resources.Definition.Decode(new Reader(plainText), ID)}");

                Logger.Write(BitConverter.ToString(plainText).Replace("-", string.Empty), $"{ID}_{Name}",
                             LogType.PACKET);
            }
        }
Esempio n. 2
0
        private static Route GenerateRoute(IList <NodeInfo> possibleNodes, int startSequenceId = 0, Route oldRoute = null)
        {
            var nodes = new RouteNode[3];
            var i     = 0;

            while (i < nodes.Length)
            {
                var nodeIndex = SodiumCore.GetRandomNumber(possibleNodes.Count);
                var node      = possibleNodes[nodeIndex];

                if (nodes.Any(n => n != null && n.Node.Id == node.Id))
                {
                    continue;
                }

                var keyPair = PublicKeyBox.GenerateKeyPair();

                nodes[i++] = new RouteNode
                {
                    EphemeralPublicKey = keyPair.PublicKey,
                    SymmetricKey       = GenerateSymmetricKey(node.PublicKey, null, keyPair.PublicKey, keyPair.PrivateKey),
                    Node = node
                };
            }

            return(new Route
            {
                StartSequenceId = startSequenceId,
                OldRoute = oldRoute,
                Nodes = nodes
            });
        }
Esempio n. 3
0
        public static void EncryptPacket(Socket socket, ServerState state, int messageId, int unknown, byte[] plainText)
        {
            byte[] cipherText;
            if (messageId == 20100)
            {
                cipherText = plainText;
            }
            else if (messageId == 20104)
            {
                var nonce =
                    GenericHash.Hash(
                        state.clientState.nonce.Concat(state.clientKey).Concat(state.serverKey.PublicKey).ToArray(),
                        null, 24);
                plainText  = state.nonce.Concat(state.sharedKey).Concat(plainText).ToArray();
                cipherText = PublicKeyBox.Create(plainText, nonce, state.serverKey.PrivateKey, state.clientKey);
            }
            else
            {
                cipherText = SecretBox.Create(plainText, state.nonce, state.sharedKey).Skip(16).ToArray();
            }
            var packet =
                BitConverter.GetBytes(messageId)
                .Reverse()
                .Skip(2)
                .Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1))
                .Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2))
                .Concat(cipherText)
                .ToArray();

            socket.BeginSend(packet, 0, packet.Length, 0, SendCallback, state);
        }
Esempio n. 4
0
        /// <summary>
        /// Internal implementation to decrypt a message given a public key and nonce
        /// </summary>
        /// <param name="response">The byte array encrypted message</param>
        /// <param name="publicKey">32 byte public key</param>
        /// <param name="nonce">24 byte nonce</param>
        /// <returns>Decrypted message as a string</returns>
        private String DecryptBody(byte[] response, byte[] publicKey, byte[] nonce)
        {
            if (publicKey.Length != PublicKeyBox.PublicKeyBytes)
            {
                throw new ArgumentException(String.Format("Public key should be %d bytes.", PublicKeyBox.PublicKeyBytes));
            }

            if (nonce.Length < 24)   // PublicKeyBox.NONCEBYTES
            {
                throw new ArgumentException(String.Format("Message should be at minimum %d bytes.", 2));
            }

            if (response.Length < 16)   // PublicKeyBox.MAC_BYTES
            {
                throw new ArgumentException(String.Format("Message should be at minimum %d bytes.", 16));
            }

            try {
                byte[] message = PublicKeyBox.Open(
                    response,
                    nonce,
                    this.secretKey,
                    publicKey
                    );

                return(System.Text.Encoding.UTF8.GetString(message));
            } catch (Exception e) {
                throw new DecryptionFailedException("Unable to decrypt message.", e);
            }
        }
        public void DetachedBoxTest()
        {
            var    alice   = PublicKeyBox.GenerateKeyPair();
            var    bob     = PublicKeyBox.GenerateKeyPair();
            var    nonce   = PublicKeyBox.GenerateNonce();
            String message = "Hello, World!";

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);

            var e1 = PublicKeyBox.CreateDetached(message, nonce, bob.Secret, alice.Public);
            var e2 = PublicKeyBox.CreateDetached(message, nonce, bob.Secret, alice.Public);

            Assert.AreEqual(Convert.ToBase64String(e1.Cipher), Convert.ToBase64String(e2.Cipher));
            Assert.AreEqual(Convert.ToBase64String(e1.Mac), Convert.ToBase64String(e2.Mac));

            var d1 = PublicKeyBox.OpenDetached(e1, nonce, alice.Secret, bob.Public);
            var d2 = PublicKeyBox.OpenDetached(e2, nonce, alice.Secret, bob.Public);

            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d1));
            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d2));

            d1 = PublicKeyBox.OpenDetached(e1.Cipher, e1.Mac, nonce, alice.Secret, bob.Public);
            d2 = PublicKeyBox.OpenDetached(e2.Cipher, e2.Mac, nonce, alice.Secret, bob.Public);

            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d1));
            Assert.AreEqual(message, System.Text.Encoding.UTF8.GetString(d2));
        }
Esempio n. 6
0
        public static void GenerateNodeKeys()
        {
            var rng      = new RNGCryptoServiceProvider();
            var id       = new byte[8];
            var idReader = new ReadBuffer(id, 0);
            var nodes    = new NodeInfo[30];

            for (var i = 0; i < nodes.Length; i++)
            {
                var keyPair = PublicKeyBox.GenerateKeyPair();
                rng.GetBytes(id);

                nodes[i] = new NodeInfo
                {
                    Address   = IPAddress.Any.GetAddressBytes(),
                    Port      = 57120 + i,
                    PublicKey = keyPair.PublicKey
                };

                idReader.Read(out nodes[i].Id);
                idReader.InitialPosition = 0;
                Console.WriteLine("\"{0}\",", Convert.ToBase64String(keyPair.PrivateKey));
            }

            //File.WriteAllText(@"C:\Users\Kevin.Spinar\Documents\Visual Studio 2015\Projects\tori\nodes.txt", new JavaScriptSerializer().Serialize(nodes));
        }
 private string Decrypt(string cipherText, string sendersPublicKey, byte[] nonce)
 {
     byte[] cipherBytes = Convert.FromBase64String(cipherText);
     byte[] spkBytes    = Convert.FromBase64String(sendersPublicKey);
     byte[] plainBytes  = PublicKeyBox.Open(cipherBytes, nonce, privateKey, spkBytes);
     return(Encoding.UTF8.GetString(plainBytes));
 }
Esempio n. 8
0
        public static void EncryptPacket(Socket _Socket, ServerState _State, int _PacketID, int unknown, byte[] plainText)
        {
            byte[] cipherText;

            if (_PacketID == 20100)
            {
                cipherText = plainText;
            }
            else if (_PacketID == 20103)
            {
                byte[] nonce = GenericHash.Hash(_State.clientState.nonce.Concat(_State.clientKey).Concat(_State.serverKey.PublicKey).ToArray(), null, 24);
                plainText  = _State.nonce.Concat(_State.sharedKey).Concat(plainText).ToArray();
                cipherText = PublicKeyBox.Create(plainText, nonce, _State.serverKey.PrivateKey, _State.clientKey);
            }
            else if (_PacketID == 20104)
            {
                byte[] nonce = GenericHash.Hash(_State.clientState.nonce.Concat(_State.clientKey).Concat(_State.serverKey.PublicKey).ToArray(), null, 24);
                plainText  = _State.nonce.Concat(_State.sharedKey).Concat(plainText).ToArray();
                cipherText = PublicKeyBox.Create(plainText, nonce, _State.serverKey.PrivateKey, _State.clientKey);
            }
            else
            {
                cipherText = SecretBox.Create(plainText, _State.nonce, _State.sharedKey).Skip(16).ToArray();
            }

            byte[] packet = BitConverter.GetBytes(_PacketID).Reverse().Skip(2).Concat(BitConverter.GetBytes(cipherText.Length).Reverse().Skip(1)).Concat(BitConverter.GetBytes(unknown).Reverse().Skip(2)).Concat(cipherText).ToArray();
            _Socket.BeginSend(packet, 0, packet.Length, 0, SendCallback, _State);
        }
Esempio n. 9
0
 public void Decrypt()
 {
     try
     {
         if (m_vType == 10101)
         {
             byte[] cipherText = m_vData;
             Client.CPublicKey = cipherText.Take(32).ToArray();
             Client.CSharedKey = Client.CPublicKey;
             Client.CRNonce    = Client.GenerateSessionKey();
             byte[] nonce = GenericHash.Hash(Client.CPublicKey.Concat(Key.Crypto.PublicKey).ToArray(), null, 24);
             cipherText = cipherText.Skip(32).ToArray();
             var PlainText = PublicKeyBox.Open(cipherText, nonce, Key.Crypto.PrivateKey, Client.CPublicKey);
             Client.CSessionKey = PlainText.Take(24).ToArray();
             Client.CSNonce     = PlainText.Skip(24).Take(24).ToArray();
             SetData(PlainText.Skip(24).Skip(24).ToArray());
         }
         else
         {
             Client.CSNonce = Utilities.Increment(Utilities.Increment(Client.CSNonce));
             SetData(SecretBox.Open(new byte[16].Concat(m_vData).ToArray(), Client.CSNonce, Client.CSharedKey));
         }
     }
     catch (Exception ex)
     {
         Client.CState = 0;
         return;
     }
 }
        private void HandshakeWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            IPEndPoint a = new IPEndPoint(IPAddress.Any, 1);

            localPair = PublicKeyBox.GenerateKeyPair();
            var message = Encoding.ASCII.GetBytes("Key");

            message = message.Concat(randomID)
                      .Concat(localPair.PublicKey)
                      .Concat(Encoding.ASCII.GetBytes(name))
                      .ToArray();
            socket.Send(message, message.Length);
            var response = socket.Receive(ref a);

            if (Encoding.ASCII.GetString(response.Take(3).ToArray()) != "Key" || response.Length != 35)
            {
                HandshakeWorker.ReportProgress(2);
                return;
            }
            remotePublicKey = response.Skip(3).Take(32).ToArray();
            message         = Encoding.ASCII.GetBytes("Ses").Concat(randomID).ToArray();
            socket.Send(message, message.Length);
            response = socket.Receive(ref a);
            if (Encoding.ASCII.GetString(response.Take(3).ToArray()) != "AOk" || response.Length != 7)
            {
                HandshakeWorker.ReportProgress(2);
                return;
            }
            sessionID = response.Skip(3).Take(4).ToArray();
            HandshakeWorker.ReportProgress(1);
        }
Esempio n. 11
0
        public async Task WorkWithImageFileAndWrongKeyTestAsync()
        {
            var          rawFile         = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var          outputDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "Testfiles", "decrypted");
            const string privateKey      = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string publicKey       = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var          keyPair         = new KeyPair(Utilities.HexToBinary(publicKey), Utilities.HexToBinary(privateKey));
            var          testKeyPair     = PublicKeyBox.GenerateKeyPair();

            Console.Write("Encrypting testfile . . .\n");
            //encrypt the file with an ephmeral key
            var encryptedFile =
                await
                Cryptor.EncryptFileWithStreamAsync(keyPair, testKeyPair.PublicKey, rawFile, null, outputDirectory,
                                                   ".test", true);

            Console.Write("Decrypting testfile . . .\n");
            //try to decrypt with an wrong key
            var decryptedFile =
                Assert.ThrowsAsync <CryptographicException>(
                    async() => await
                    Cryptor.DecryptFileWithStreamAsync(keyPair,
                                                       Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile),
                                                       outputDirectory));


            File.Delete(Path.Combine(TestContext.CurrentContext.TestDirectory, outputDirectory, encryptedFile));
        }
        public void TestLoggerEncryption()
        {
            var     result          = LoggerHelper.CreateLogger("Deim Vadder sein Service", null, null);
            var     logger          = result.logger;
            dynamic logResult       = new ExpandoObject();
            bool    exceptionThrown = false;

            try
            {
                LoggerHelper.CreateTraceObject("das ist ein verschlüsselter test", true, "Köaäasdaspfe");
            }
            catch (FormatException)
            {
                exceptionThrown = true;
            }
            Assert.True(exceptionThrown);
            var keyPair     = PublicKeyBox.GenerateKeyPair();
            var traceObject = LoggerHelper.CreateTraceObject("das ist ein verschlüsselter test", true, Convert.ToBase64String(keyPair.PublicKey));

            logger.LogTrace(traceObject);
            var message = result.loggerProvider.Messages[0].Message;

            Encrypter       dec     = new AsymmetricEncrypter(keyPair.PrivateKey);
            JToken          content = JObject.Parse(message).GetValue("Content");
            EncryptedObject eo      = JsonConvert.DeserializeObject <EncryptedObjectPublicKeyBox>(content.ToString());
            BusinessObject  bo      = dec.Decrypt(eo);

            Assert.NotNull(bo);
            Assert.Equal(1, bo.VersionStruktur);
            LogObject lo = bo as LogObject;

            Assert.Equal("das ist ein verschlüsselter test", lo.LogMessage);
        }
Esempio n. 13
0
        /// <summary>
        /// Takes a 'plaintext' Buffer of the message you want to encrypt,<para />
        /// and an array of recipient public keys.<para />
        /// Returns a message that is encrypted to all recipients<para />
        /// and openable by them with 'PrivateBox.MultiboxOpen'.<para />
        /// The 'recipients' must be between 1 and 7 items long.
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="recipients"></param>
        /// <param name="maxRecipients"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static byte[] Multibox(byte[] msg, byte[][] recipients, int maxRecipients = DEFAULT_MAX)
        {
            if (maxRecipients < 1 || maxRecipients > 255)
            {
                throw new ArgumentOutOfRangeException("max recipients must be between 1 and 255.");
            }

            if (recipients.Length > maxRecipients)
            {
                throw new ArgumentOutOfRangeException("max recipients is:" + maxRecipients + " found:" + recipients.Length);
            }

            var nonce   = RandomBytes(24);
            var key     = RandomBytes(32);
            var onetime = PublicKeyBox.GenerateKeyPair();

            var length_and_key = new List <byte>();

            length_and_key.Add((byte)recipients.Length);
            length_and_key.AddRange(key);

            var res = new List <byte>();

            res.AddRange(nonce);
            res.AddRange(onetime.PublicKey);

            foreach (var rec in recipients)
            {
                res.AddRange(SecretBox.Create(length_and_key.ToArray(), nonce, ScalarMult.Mult(onetime.PrivateKey, rec)));
            }
            res.AddRange(SecretBox.Create(msg, nonce, key));

            return(res.ToArray());
        }
Esempio n. 14
0
 public void Encrypt(byte[] plainText)
 {
     try
     {
         if (GetMessageType() == 20103)
         {
             byte[] nonce = GenericHash.Hash(Client.CSNonce.Concat(Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray(), null, 24);
             plainText = Client.CRNonce.Concat(Client.CSharedKey).Concat(plainText).ToArray();
             SetData(PublicKeyBox.Create(plainText, nonce, Key.Crypto.PrivateKey, Client.CPublicKey));
         }
         else if (GetMessageType() == 20104)
         {
             byte[] nonce = GenericHash.Hash(Client.CSNonce.Concat(Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray(), null, 24);
             plainText = Client.CRNonce.Concat(Client.CSharedKey).Concat(plainText).ToArray();
             SetData(PublicKeyBox.Create(plainText, nonce, Key.Crypto.PrivateKey, Client.CPublicKey));
             Client.CState = 2;
         }
         else
         {
             Client.CRNonce = Utilities.Increment(Utilities.Increment(Client.CRNonce));
             SetData(SecretBox.Create(plainText, Client.CRNonce, Client.CSharedKey).Skip(16).ToArray());
         }
     }
     catch (Exception ex)
     {
         Client.CState = 0;
     }
 }
Esempio n. 15
0
 public void Decrypt()
 {
     try
     {
         if (this.m_vType == 10101)
         {
             byte[] array = this.m_vData;
             this.Client.CPublicKey = array.Take(32).ToArray <byte>();
             this.Client.CSharedKey = this.Client.CPublicKey;
             this.Client.CRNonce    = Client.GenerateSessionKey();
             byte[] nonce = GenericHash.Hash(this.Client.CPublicKey.Concat(Key.Crypto.PublicKey).ToArray <byte>(), null, 24);
             array = array.Skip(32).ToArray <byte>();
             byte[] source = PublicKeyBox.Open(array, nonce, Key.Crypto.PrivateKey, this.Client.CPublicKey);
             this.Client.CSessionKey = source.Take(24).ToArray <byte>();
             this.Client.CSNonce     = source.Skip(24).Take(24).ToArray <byte>();
             this.SetData(source.Skip(24).Skip(24).ToArray <byte>());
         }
         else
         {
             this.Client.CSNonce = Sodium.Utilities.Increment(Sodium.Utilities.Increment(this.Client.CSNonce));
             this.SetData(SecretBox.Open(new byte[16].Concat(this.m_vData).ToArray <byte>(), this.Client.CSNonce, this.Client.CSharedKey));
         }
     }
     catch (Exception)
     {
         this.Client.CState = 0;
     }
 }
Esempio n. 16
0
        public static Dictionary <string, string> Encrypt(string message, string secretKey, string publicKey)
        {
            byte[] nonce = GenerateNonce();
            byte[] secret_bytes;
            byte[] public_bytes;
            if (!Utils.IsBase64(secretKey))
            {
                secret_bytes = Encoding.ASCII.GetBytes(secretKey);
            }
            else
            {
                secret_bytes = Convert.FromBase64String(secretKey);
            }

            if (!Utils.IsBase64(publicKey))
            {
                public_bytes = Encoding.ASCII.GetBytes(publicKey);
            }
            else
            {
                public_bytes = Convert.FromBase64String(publicKey);
            }

            var crypt = PublicKeyBox.Create(message, nonce, secret_bytes, public_bytes);

            return(new Dictionary <string, string>()
            {
                { "nonce", Convert.ToBase64String(nonce) },
                { "crypt", Convert.ToBase64String(crypt) }
            });
        }
Esempio n. 17
0
 public void Encrypt(byte[] plainText)
 {
     try
     {
         if (this.GetMessageType() == 20103)
         {
             byte[] nonce = GenericHash.Hash(this.Client.CSNonce.Concat(this.Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray <byte>(), null, 24);
             plainText = this.Client.CRNonce.Concat(this.Client.CSharedKey).Concat(plainText).ToArray <byte>();
             this.SetData(PublicKeyBox.Create(plainText, nonce, Key.Crypto.PrivateKey, this.Client.CPublicKey));
         }
         else if (this.GetMessageType() == 20104)
         {
             byte[] nonce2 = GenericHash.Hash(this.Client.CSNonce.Concat(this.Client.CPublicKey).Concat(Key.Crypto.PublicKey).ToArray <byte>(), null, 24);
             plainText = this.Client.CRNonce.Concat(this.Client.CSharedKey).Concat(plainText).ToArray <byte>();
             this.SetData(PublicKeyBox.Create(plainText, nonce2, Key.Crypto.PrivateKey, this.Client.CPublicKey));
             this.Client.CState = 2;
         }
         else
         {
             this.Client.CRNonce = Sodium.Utilities.Increment(Sodium.Utilities.Increment(this.Client.CRNonce));
             this.SetData(SecretBox.Create(plainText, this.Client.CRNonce, this.Client.CSharedKey).Skip(16).ToArray <byte>());
         }
     }
     catch (Exception)
     {
         this.Client.CState = 0;
     }
 }
Esempio n. 18
0
        /// <summary>
        ///     Generate a CurveLock Keypair from an email and a password.
        /// </summary>
        /// <param name="email">A valid (format) email address.</param>
        /// <param name="password">A password.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="InvalidMailException"></exception>
        /// <returns>A libsodium compatible KeyPair.</returns>
        public static KeyPair GenerateCurveLockKeyPair(string email, string password)
        {
            if (email == null)
            {
                throw new ArgumentNullException("email", "email cannot be null");
            }

            // perform a simple email check
            if (!StringHelper.IsValidEmail(email))
            {
                throw new InvalidMailException("the given email address seems to be invalid");
            }

            if (password == null)
            {
                throw new ArgumentNullException("password", "password cannot be null");
            }

            var salt = GenericHash.Hash(email, (byte[])null, 32);
            var seed = PasswordHash.ScryptHashBinary(Encoding.UTF8.GetBytes(password), salt,
                                                     PasswordHash.Strength.MediumSlow);
            var key = PublicKeyBox.GenerateKeyPair(seed);

            return(key);
        }
Esempio n. 19
0
        public async void WorkWithImageFileAndWrongKeyTestAsync()
        {
            var          RAW_FILE         = Path.Combine("Testfiles", "MyAwesomeChipmunkKiller.jpg");
            var          OUTPUT_DIRECTORY = Path.Combine("Testfiles", "decrypted");
            const string PRIVATE_KEY      = "31d9040b00a170532929b37db0afcb989e4175f96e5f9667ee8cbf5706679a71";
            const string PUBLIC_KEY       = "6d0deec730700f9f60687a4e6e8755157ca22ea2f3815b9bf14b1fe9ae6a0b4d";
            var          keyPair          = new KeyPair(Utilities.HexToBinary(PUBLIC_KEY), Utilities.HexToBinary(PRIVATE_KEY));
            var          testKeyPair      = PublicKeyBox.GenerateKeyPair();

            Console.Write("Encrypting testfile . . .\n");
            //encrypt the file with an ephmeral key
            var encryptedFile =
                await
                Cryptor.EncryptFileWithStreamAsync(keyPair, testKeyPair.PublicKey, RAW_FILE, null, OUTPUT_DIRECTORY,
                                                   ".test", true);

            Console.Write("Decrypting testfile . . .\n");
            //try to decrypt with an wrong key
            var decryptedFile =
                await
                Cryptor.DecryptFileWithStreamAsync(keyPair, Path.Combine(OUTPUT_DIRECTORY, encryptedFile),
                                                   OUTPUT_DIRECTORY);

            Console.Write("Get checksum of testfiles . . .\n");
            Assert.AreEqual(Utils.GetChecksum(RAW_FILE),
                            Utils.GetChecksum(Path.Combine(OUTPUT_DIRECTORY, decryptedFile)));
            //clear garbage
            File.Delete(Path.Combine(OUTPUT_DIRECTORY, encryptedFile));
            File.Delete(Path.Combine(OUTPUT_DIRECTORY, decryptedFile));
        }
Esempio n. 20
0
        public void GenerateKeyPairTest()
        {
            var kp = PublicKeyBox.GenerateKeyPair();

            Assert.AreEqual(32, kp.Public.Length);
            Assert.AreEqual(32, kp.Secret.Length);
        }
Esempio n. 21
0
        public static void AcceptCallback(IAsyncResult Result)
        {
            try
            {
                Wait.Set();

                var socket = (Result.AsyncState as Socket).EndAccept(Result);

                var state = new ServerState
                {
                    Socket    = socket,
                    ServerKey = PublicKeyBox.GenerateKeyPair(Key.PrivateKey)
                };

                Console.WriteLine($"Accepted new client {socket.RemoteEndPoint}.");

                var client = new Client();
                client.State.ServerState = state;
                state.ClientState        = client.State;

                socket.BeginReceive(state.Buffer, 0, State.BufferSize, 0, ReceiveCallback, state);
            }
            catch (Exception)
            {
            }
        }
Esempio n. 22
0
        public static void DecryptPacket(Socket socket, ServerState state, byte[] packet)
        {
            var messageId     = BitConverter.ToInt32(new byte[2].Concat(packet.Take(2)).Reverse().ToArray(), 0);
            var payloadLength = BitConverter.ToInt32(new byte[1].Concat(packet.Skip(2).Take(3)).Reverse().ToArray(), 0);
            var unknown       = BitConverter.ToInt32(new byte[2].Concat(packet.Skip(2).Skip(3).Take(2)).Reverse().ToArray(), 0);
            var cipherText    = packet.Skip(2).Skip(3).Skip(2).ToArray();

            byte[] plainText;

            if (messageId == 10100)
            {
                plainText = cipherText;
            }
            else if (messageId == 10101)
            {
                state.clientKey = cipherText.Take(32).ToArray();
                var nonce = GenericHash.Hash(state.clientKey.Concat(state.serverKey.PublicKey).ToArray(), null, 24);
                cipherText              = cipherText.Skip(32).ToArray();
                plainText               = PublicKeyBox.Open(cipherText, nonce, state.serverKey.PrivateKey, state.clientKey);
                state.sessionKey        = plainText.Take(24).ToArray();
                state.clientState.nonce = plainText.Skip(24).Take(24).ToArray();
                plainText               = plainText.Skip(24).Skip(24).ToArray();
            }
            else
            {
                state.clientState.nonce = Utilities.Increment(Utilities.Increment(state.clientState.nonce));
                plainText = SecretBox.Open(new byte[16].Concat(cipherText).ToArray(), state.clientState.nonce,
                                           state.sharedKey);
            }
            Console.WriteLine("[UCR]    {0}" + Environment.NewLine + "{1}", PacketInfos.GetPacketName(messageId),
                              Utilities.BinaryToHex(packet.Take(7).ToArray()) + Utilities.BinaryToHex(plainText));
            ClientCrypto.EncryptPacket(state.clientState.socket, state.clientState, messageId, unknown, plainText);
        }
Esempio n. 23
0
 public void PublicKeyBoxOpenBadNonce()
 {
     PublicKeyBox.Open(
         Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"),
         Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
         Utilities.HexToBinary("d4c8438482d5d103a2315251a5eed7c46017864a02ddc4c8b03f0ede8cb3ef9b"),
         Utilities.HexToBinary("753cb95919b15b76654b1969c554a4aaf8334402ef1468cb40a602b9c9fd2c13"));
 }
Esempio n. 24
0
 public void preKeyGeneration()
 {
     // Generate 16 prekeys
     for (int i = 0; i < 16; i++)
     {
         preKeys.Add(PublicKeyBox.GenerateSeededKeyPair(PublicKeyBox.GenerateNonce()));
     }
 }
Esempio n. 25
0
 public static KeyPair GenerateKeyPair(byte[] seed = null)
 {
     if (seed is null)
     {
         return(PublicKeyBox.GenerateKeyPair());
     }
     return(PublicKeyBox.GenerateKeyPair(seed));
 }
Esempio n. 26
0
        public static string AnonymousRSADecryption(string privateKey, string cipherText)
        {
            var encodedPrivateKey = Encoding.UTF8.GetBytes(privateKey);
            var keyPair           = PublicKeyBox.GenerateKeyPair(encodedPrivateKey);
            var plainText         = SealedPublicKeyBox.Open(cipherText, keyPair);

            return(Encoding.UTF8.GetString(plainText));
        }
Esempio n. 27
0
 public void PublicKeyBoxCreateWithBadNonce()
 {
     PublicKeyBox.Create(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVX"),
         Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
         Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
 }
        public void GenerateKeyTest()
        {
            var actual = PublicKeyBox.GenerateKeyPair();

            //need a better test
            Assert.IsNotNull(actual.PrivateKey);
            Assert.IsNotNull(actual.PublicKey);
        }
Esempio n. 29
0
        public static KeyPair ScryptGenerateKey(string email, string password)
        {
            var salt = GenericHash.Hash(email, (byte[])null, 32);
            var seed = PasswordHash.ScryptHashBinary(Encoding.UTF8.GetBytes(password), salt, PasswordHash.Strength.MediumSlow);
            var key  = PublicKeyBox.GenerateKeyPair(seed);

            return(key);
        }
Esempio n. 30
0
        public static (string, string) GenerateKeyPair()
        {
            using var keyPair = PublicKeyBox.GenerateKeyPair();
            string publicKey  = Convert.ToBase64String(keyPair.PublicKey);
            string privateKey = Convert.ToBase64String(keyPair.PrivateKey);

            return(publicKey, privateKey);
        }