Exemplo n.º 1
0
        private void DeserializeObjects(Block block, byte[] data)
        {
            using (var ms = new MemoryStream(data))
            {
                using (var br = new BinaryReader(ms))
                {
                    // Version:
                    var context = new BlockDeserializeContext(br, _typeProvider);

                    // Nonce:
                    var nonce = context.br.ReadBuffer();
                    if (nonce != null)
                    {
                        // Data:
                        using (var dms = new MemoryStream(StreamEncryption.EncryptChaCha20(context.br.ReadBuffer(), nonce, _typeProvider.SecretKey)))
                        {
                            using (var dbr = new BinaryReader(dms))
                            {
                                var dc = new BlockDeserializeContext(dbr, _typeProvider);
                                block.DeserializeObjects(dc);
                            }
                        }
                    }
                    else
                    {
                        // Data:
                        block.DeserializeObjects(context);
                    }
                }
            }
        }
 public void StreamEncryptionEncryptChaCha20BadKey()
 {
     StreamEncryption.EncryptChaCha20(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABCDEFGH"),
         Encoding.UTF8.GetBytes("123456789012345678901234567890"));
 }
Exemplo n.º 3
0
    private void Start()
    {
        int x = NativeLibsodium.sodium_init();

        Debug.Log(x);


        const string MESSAGE = "Test message to encrypt";

        byte[] nonce = StreamEncryption.GenerateNonceChaCha20();
        byte[] key   = StreamEncryption.GenerateKey();

        //encrypt it
        byte[] encrypted = StreamEncryption.EncryptChaCha20(MESSAGE, nonce, key);


        //decrypt it
        byte[] decrypted = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

        string str_origin    = MESSAGE;
        string str_encrypted = Encoding.UTF8.GetString(encrypted);
        string str_decrypted = Encoding.UTF8.GetString(decrypted);

        Debug.Log(str_origin);
        Debug.Log(str_encrypted);
        Debug.Log(str_decrypted);

        txt_origin.text    = str_origin;
        txt_encrypted.text = str_encrypted;
        txt_decrypted.text = str_decrypted;
    }
 public void StreamEncryptionEncryptChaCha20BadNonce()
 {
     StreamEncryption.EncryptChaCha20(
         Encoding.UTF8.GetBytes("Adam Caudill"),
         Encoding.UTF8.GetBytes("ABC"),
         Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
 }
Exemplo n.º 5
0
        public ConnectPacketData GetConnectPacket()
        {
            var connectPacketData = new ConnectPacketData
            {
                AddressType  = _connection.AddressType,
                DestPort     = _connection.DestPort,
                RouteCount   = (uint)_connection.ReturnRoutes.Length,
                ReturnRoutes = // TODO
            };

            if (_connection.AddressType == DestAddressType.DomainName)
            {
                connectPacketData.DestDomainName = _connection.DestDomainName;
            }
            else
            {
                connectPacketData.DestIpAddress = _connection.DestIpAddress;
            }

            var bytesToEncrypt = new byte[PacketContent.MaxSendDataLen + 27];

            var buffer = new WriteBuffer(bytesToEncrypt, 0);

            buffer.Write(_connection.UserId);
            buffer.Write(_connection.ConnectionId);
            buffer.Write(_connection.NextSequenceId);
            buffer.Write((byte)PacketDataType.Connect);
            buffer.Write(connectPacketData);
            var paddingLength = bytesToEncrypt.Length - buffer.TotalWritten;

            buffer.Write(new byte[paddingLength]);

            var route     = GenerateRoute(_possibleNodes);
            var encrypted = SecretBox.Create(bytesToEncrypt, OneNonce, route.Nodes[2].SymmetricKey);

            var destIdAndDataLen = new byte[10];

            buffer.Buffer = destIdAndDataLen;
            buffer.Write((ulong)0);
            buffer.Write((ushort)(encrypted.Length - 16));

            var innerPacketBytes = new byte[bytesToEncrypt.Length + 67];

            buffer.Buffer = innerPacketBytes;

            buffer.Write(route.Nodes[2].Node.Id);
            buffer.Write(route.Nodes[2].EphemeralPublicKey);
            buffer.Write((byte)(route.Nodes[2].SymmetricKey[31] & 1));
            buffer.Write(StreamEncryption.EncryptChaCha20(destIdAndDataLen, ZeroNonce, route.Nodes[2].SymmetricKey));
            buffer.Write(encrypted);

            encrypted = SecretBox.Create(encrypted, OneNonce, route.Nodes[2].SymmetricKey);

            var destId = new byte[8];

            buffer.Buffer = destId;
            buffer.Write(route.Nodes[1].Node.Id);
        }
 public void CreateSecretBoxChaCha20()
 {
     var expected = Utilities.HexToBinary("a6ce598d8b865fb328581bcd");
     var actual = StreamEncryption.EncryptChaCha20(
       Encoding.UTF8.GetBytes("Adam Caudill"),
       Encoding.UTF8.GetBytes("ABCDEFGH"),
       Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     Assert.AreEqual(expected, actual);
 }
 public void StreamEncryptionEncryptChaCha20BadNonce()
 {
     Assert.Throws <NonceOutOfRangeException>(() =>
     {
         StreamEncryption.EncryptChaCha20(
             Encoding.UTF8.GetBytes("Adam Caudill"),
             Encoding.UTF8.GetBytes("ABC"),
             Encoding.UTF8.GetBytes("12345678901234567890123456789012"));
     });
 }
        public void Stream_Encryption_Basic()
        {
            var nonce         = StreamEncryption.GenerateNonceChaCha20();
            var key           = StreamEncryption.GenerateKey();
            var messageString = "Test message to encrypt";
            var encrypted     = StreamEncryption.EncryptChaCha20(messageString, nonce, key);
            var decrypted     = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

            Assert.AreEqual(messageString, Encoding.UTF8.GetString(decrypted));
        }
    public byte[] Encrypt(byte[] message, long nonce, bool isInvalidClientPayload = false)
    {
        byte[] messageVar = new byte[] { };
        if (isInvalidClientPayload)
        {
            messageVar = StreamEncryption.EncryptChaCha20(message, BitConverter.GetBytes(nonce), Convert.FromBase64String(ChaChaEncryptionKey2));
        }
        else
        {
            messageVar = StreamEncryption.EncryptChaCha20(message, BitConverter.GetBytes(nonce), Convert.FromBase64String(ChaChaEncryptionKey));
        }

        return(messageVar);
    }
        public void ChaCha20Test()
        {
            var    key     = StreamEncryption.GenerateKey();
            var    nonce   = StreamEncryption.GenerateNonceChaCha20();
            string message = "Hello, World!";

            var cipherText = StreamEncryption.EncryptChaCha20(message, nonce, key);
            var decrypted  = StreamEncryption.DecryptChaCha20(cipherText, nonce, key);

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

            byte[] byteMessage = System.Text.Encoding.UTF8.GetBytes(message);
            cipherText = StreamEncryption.EncryptChaCha20(byteMessage, nonce, key);
            decrypted  = StreamEncryption.DecryptChaCha20(cipherText, nonce, key);
            Assert.AreEqual(Convert.ToBase64String(byteMessage), Convert.ToBase64String(decrypted));
        }
Exemplo n.º 11
0
        public void TestChaCha20()
        {
            int x = NativeLibsodium.sodium_init();

            Assert.True(x == 0 || x == 1);

            const string MESSAGE = "Test message to encrypt";

            byte[] nonce = StreamEncryption.GenerateNonceChaCha20();
            byte[] key   = StreamEncryption.GenerateKey();

            //encrypt it
            byte[] encrypted = StreamEncryption.EncryptChaCha20(MESSAGE, nonce, key);


            //decrypt it
            byte[] decrypted = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

            Assert.AreEqual(MESSAGE, decrypted);
        }
Exemplo n.º 12
0
        private byte[] SerializeObjects(Block block)
        {
            byte[] data;
            using (var ms = new MemoryStream())
            {
                using (var bw = new BinaryWriter(ms, Encoding.UTF8))
                {
                    // Version:
                    var context = new BlockSerializeContext(bw, _typeProvider);

                    if (context.typeProvider.SecretKey != null)
                    {
                        // Nonce:
                        var nonce = StreamEncryption.GenerateNonceChaCha20();
                        context.bw.WriteBuffer(nonce);

                        // Data:
                        using (var ems = new MemoryStream())
                        {
                            using (var ebw = new BinaryWriter(ems, Encoding.UTF8))
                            {
                                var ec = new BlockSerializeContext(ebw, _typeProvider, context.Version);
                                block.SerializeObjects(ec);
                                context.bw.WriteBuffer(StreamEncryption.EncryptChaCha20(ems.ToArray(), nonce, ec.typeProvider.SecretKey));
                            }
                        }
                    }
                    else
                    {
                        // Data:
                        context.bw.Write(false);
                        block.SerializeObjects(context);
                    }

                    data = ms.ToArray();
                }
            }

            return(data);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Encrypt a message using provided key and nonce
 /// </summary>
 /// <param name="message">Plaintext message</param>
 /// <param name="key">Plaintext/Base64-encoded key</param>
 /// <param name="nonce">Base64-encoded nonce (generate using GenerateNonce())</param>
 /// <returns>
 /// Base64-encoded encrypted message
 /// </returns>
 public static string Encrypt(string message, string key, string nonce)
 {
     // Validate parameters
     if (string.IsNullOrEmpty(key))
     {
         throw new ArgumentNullException(nameof(key));
     }
     if (string.IsNullOrEmpty(message))
     {
         throw new ArgumentNullException(nameof(message));
     }
     if (string.IsNullOrEmpty(nonce))
     {
         throw new ArgumentNullException(nameof(nonce));
     }
     // Check nonce is Base64
     if (!Utils.IsBase64(nonce))
     {
         throw new ArgumentException($"{nameof(nonce)} must be base64-encoded string");
     }
     byte[] nonce_bytes = Convert.FromBase64String(nonce);
     // Convert key to bytes
     byte[] key_bytes;
     if (Utils.IsBase64(key))
     {
         // Key is Base64, convert to raw bytes
         key_bytes = Convert.FromBase64String(key);
     }
     else
     {
         // Key is plaintext string, fallback to raw ASCII bytes
         key_bytes = Encoding.ASCII.GetBytes(key);
     }
     // Encrypt the message
     byte[] encrypted = StreamEncryption.EncryptChaCha20(message, nonce_bytes, key_bytes);
     // Return the raw bytes as Base64
     return(Convert.ToBase64String(encrypted));
 }
Exemplo n.º 14
0
    private void Start()
    {
        int x = NativeLibsodium.sodium_init();

        Debug.Log(x);


        const string MESSAGE = "Test message to encrypt";

        byte[] nonce = StreamEncryption.GenerateNonceChaCha20();
        byte[] key   = StreamEncryption.GenerateKey();

        //encrypt it
        byte[] encrypted = StreamEncryption.EncryptChaCha20(MESSAGE, nonce, key);


        //decrypt it
        byte[] decrypted = StreamEncryption.DecryptChaCha20(encrypted, nonce, key);

        Debug.Log(MESSAGE);
        Debug.Log(Encoding.UTF8.GetString(encrypted));
        Debug.Log(Encoding.UTF8.GetString(decrypted));
    }
Exemplo n.º 15
0
        public void RoundTripCheck(IHashProvider hashProvider, IBlockObjectTypeProvider typeProvider)
        {
            // Serialize a first time
            var firstMemoryStream     = new MemoryStream();
            var firstSerializeContext = new BlockSerializeContext(new BinaryWriter(firstMemoryStream), typeProvider);

            byte[] nonce;
            if (typeProvider.SecretKey != null)
            {
                nonce = StreamEncryption.GenerateNonceChaCha20();
                firstSerializeContext.bw.WriteBuffer(nonce);
                using (var ems = new MemoryStream())
                {
                    using (var ebw = new BinaryWriter(ems))
                    {
                        var ec = new BlockSerializeContext(ebw, typeProvider, firstSerializeContext.Version);
                        Serialize(ec);
                        firstSerializeContext.bw.WriteBuffer(StreamEncryption.EncryptChaCha20(ems.ToArray(), nonce, ec.typeProvider.SecretKey));
                    }
                }
            }
            else
            {
                firstSerializeContext.bw.Write(false);
                Serialize(firstSerializeContext);
            }

            byte[] originalData = firstMemoryStream.ToArray();

            // Then deserialize that data
            {
                var br = new BinaryReader(new MemoryStream(originalData));
                var deserializeContext = new BlockDeserializeContext(br, typeProvider);
                nonce = deserializeContext.br.ReadBuffer();

                Block deserialized;
                if (nonce != null)
                {
                    using (var dms = new MemoryStream(StreamEncryption.DecryptChaCha20(deserializeContext.br.ReadBuffer(), nonce, typeProvider.SecretKey)))
                    {
                        using (var dbr = new BinaryReader(dms))
                        {
                            var dc = new BlockDeserializeContext(dbr, typeProvider);
                            deserialized = new Block(dc);
                        }
                    }
                }
                else
                {
                    deserialized = new Block(deserializeContext);
                }

                // Then serialize that deserialized data and see if it matches
                {
                    var secondMemoryStream     = new MemoryCompareStream(originalData);
                    var secondSerializeContext = new BlockSerializeContext(new BinaryWriter(secondMemoryStream), typeProvider);
                    if (typeProvider.SecretKey != null)
                    {
                        secondSerializeContext.bw.WriteBuffer(nonce);
                        using (var ems = new MemoryStream())
                        {
                            using (var ebw = new BinaryWriter(ems))
                            {
                                var ec = new BlockSerializeContext(ebw, typeProvider, secondSerializeContext.Version);
                                deserialized.Serialize(ec);
                                secondSerializeContext.bw.WriteBuffer(StreamEncryption.EncryptChaCha20(ems.ToArray(), nonce, ec.typeProvider.SecretKey));
                            }
                        }
                    }
                    else
                    {
                        secondSerializeContext.bw.Write(false);
                        deserialized.Serialize(secondSerializeContext);
                    }
                }
            }
        }
 public byte[] Encrypt(byte[] message, long nonce)
 {
     return(StreamEncryption.EncryptChaCha20(message, GetNonceBytes(nonce), _crypteKey));
 }
    public byte[] Encrypt(byte[] message, long nonce)
    {
        var nonceByte = BitConverter.GetBytes(nonce);

        return(StreamEncryption.EncryptChaCha20(message, nonceByte, ChaChaEncryptionKey));
    }
 public byte[] Encrypt_Fake(byte[] message, long tmpNonce)
 {
     return(StreamEncryption.EncryptChaCha20(message, BitConverter.GetBytes(tmpNonce), Convert.FromBase64String(ChaChaEncryptionKeyFake)));
 }