public byte[] EncodeToProtocol(Level level, byte[] timestamp, string hostName, string serviceName, string message, byte[] initVector)
        {
            byte[] bufOut = null;
            using (var stream = new MemoryStream(16 + HOST_NAME_SIZE + SERVICE_NAME_SIZE + PLUGIN_OUTPUT_SIZE))
            {
                stream.WriteShort(Nsca_VERSION); //bytes 0-1
                stream.WriteShort(0); //bytes 2-3
                stream.WriteInt(0); //bytes 4-8
                stream.Write(timestamp, 0, 4); //bytes 9-13
                stream.WriteShort((short)level); //bytes 14-15
                stream.WriteFixedString(hostName, HOST_NAME_SIZE);
                if (string.IsNullOrWhiteSpace(serviceName) == false)
                    stream.WriteFixedString(serviceName, SERVICE_NAME_SIZE); // process service check result
                else
                    stream.WriteFixedString("\x0", SERVICE_NAME_SIZE); // process host check result
                stream.WriteFixedString(message, PLUGIN_OUTPUT_SIZE);
                stream.WriteShort(0);

                int hash = CRC32.Compute(stream.ToArray());
                stream.Position = 4;
                stream.WriteInt(hash);

                var encryptor = EncryptorFactory.CreateEncryptor(settings.EncryptionType);
                bufOut = encryptor.Encrypt(stream.ToArray(), initVector, settings.Password);
            }
            return bufOut;
        }
Ejemplo n.º 2
0
 public static MemoryStream NewPkt(PktType p)
 {
     var ms = new MemoryStream();
     ms.WriteShort(_Header);
     ms.WriteShort((int)p);
     ms.WriteInt((int)ms.Length - HeadLength);
     return ms;
 }
Ejemplo n.º 3
0
        public void Receive_copies_data_from_inputStream()
        {
            var deltaStream = new MemoryStream();
            deltaStream.WriteByte(DeltaStreamer.DeltaStreamConstants.COPY_BLOCK_START_MARKER);
            deltaStream.WriteLong(4); // Start the copy from byte four
            deltaStream.WriteInt(10); // Copy 10 bytes
            deltaStream.Seek(0, SeekOrigin.Begin);

            var inputStream = new MemoryStream(); // Must have 4 + 10 bytes
            for (int i = 0; i < 20; ++i) inputStream.WriteByte((byte) (255 - i));
            inputStream.Seek(0, SeekOrigin.Begin);

            var outputStream = new MemoryStream();

            var streamer = new DeltaStreamer();
            streamer.Receive(deltaStream, inputStream, outputStream);

            Assert.AreEqual(10, outputStream.Length);
            outputStream.GetBuffer().Take(14).SequenceEqual(inputStream.GetBuffer().Skip(3).Take(14));
        }
        public byte[] EncodeToProtocol(Level level, byte[] timestamp, string hostName, string serviceName, string message, byte[] initVector)
        {
            using (var stream = new MemoryStream(16 + HOST_NAME_SIZE + SERVICE_NAME_SIZE + PLUGIN_OUTPUT_SIZE))
            {
                stream.WriteShort(NSCA_VERSION); //bytes 0-1
                stream.WriteShort(0); //bytes 2-3
                stream.WriteInt(0); //bytes 4-8
                stream.Write(timestamp, 0, 4); //bytes 9-13
                stream.WriteShort((short) level); //bytes 14-15
                stream.WriteFixedString(hostName, HOST_NAME_SIZE);
                stream.WriteFixedString(serviceName, SERVICE_NAME_SIZE);
                stream.WriteFixedString(message, PLUGIN_OUTPUT_SIZE);
                stream.WriteShort(0);

                int hash = CRC32.Compute(stream.ToArray());
                stream.Position = 4;
                stream.WriteInt(hash);

                var encryptor = EncryptorFactory.CreateEncryptor(settings.EncryptionType);
                return encryptor.Encrypt(stream.ToArray(), initVector, settings.Password);
            }
        }
Ejemplo n.º 5
0
        public static Stream Serialize(this Bin bin)
        {
            Stream serialized = new MemoryStream();

            serialized.WriteUint((uint)bin.Count);

            var alias = TypeIdentity.Instance.FindAlias(bin.GetInnerType());
            serialized.WriteUint(alias.UnicodeLength());
            serialized.WriteUnicode(alias);

            for (int i = 0; i < bin.Count; i++)
            {
                if (bin.GetInnerType() == typeof(bool))
                {
                    serialized.WriteBool((bool)bin[i]);
                }
                if (bin.GetInnerType() == typeof(int))
                {
                    serialized.WriteInt((int)bin[i]);
                }
                if (bin.GetInnerType() == typeof(float))
                {
                    serialized.WriteFloat((float)bin[i]);
                }
                if (bin.GetInnerType() == typeof(double))
                {
                    serialized.WriteDouble((double)bin[i]);
                }
                if (bin.GetInnerType() == typeof(string))
                {
                    var l = ((string)bin[i]).UnicodeLength();
                    serialized.WriteUint(l);
                    if (l>0) serialized.WriteUnicode((string)bin[i]);
                }

                if (bin.GetInnerType() == typeof(RGBAColor))
                {
                    serialized.WriteDouble(((RGBAColor)bin[i]).R);
                    serialized.WriteDouble(((RGBAColor)bin[i]).G);
                    serialized.WriteDouble(((RGBAColor)bin[i]).B);
                    serialized.WriteDouble(((RGBAColor)bin[i]).A);
                }
                if (bin.GetInnerType() == typeof(Vector2D))
                {
                    serialized.WriteDouble(((Vector2D)bin[i]).x);
                    serialized.WriteDouble(((Vector2D)bin[i]).y);
                }
                if (bin.GetInnerType() == typeof(Vector3D))
                {
                    serialized.WriteDouble(((Vector3D)bin[i]).x);
                    serialized.WriteDouble(((Vector3D)bin[i]).y);
                    serialized.WriteDouble(((Vector3D)bin[i]).z);
                }
                if (bin.GetInnerType() == typeof(Vector4D))
                {
                    serialized.WriteDouble(((Vector4D)bin[i]).x);
                    serialized.WriteDouble(((Vector4D)bin[i]).y);
                    serialized.WriteDouble(((Vector4D)bin[i]).z);
                    serialized.WriteDouble(((Vector4D)bin[i]).w);
                }
                if (bin.GetInnerType() == typeof(Matrix4x4))
                {
                    for (int j = 0; j < 16; j++)
                    {
                        serialized.WriteDouble(((Matrix4x4)bin[i]).Values[j]);
                    }
                }
                if (bin.GetInnerType() == typeof(Stream))
                {
                    var l = ((Stream)bin[i]).Length;
                    serialized.WriteUint((uint)l);
                    if (l > 0)
                    {
                        ((Stream) bin[i]).Position = 0;
                        ((Stream) bin[i]).CopyTo(serialized, (int) l);
                    }
                }
                if (bin.GetInnerType() == typeof(Time.Time))
                {
                    var t = (Time.Time) bin[i];
                    var time = t.UniversalTime.ToString("yyyy-MM-dd HH:mm:ss.ffff");
                    var zone = t.TimeZone.Id;

                    serialized.WriteUint(time.UnicodeLength());
                    serialized.WriteUnicode(time);

                    serialized.WriteUint(zone.UnicodeLength());
                    serialized.WriteUnicode(zone);
                }

            }
            serialized.Position = 0;
            return serialized;
        }
Ejemplo n.º 6
0
 public static void ClosePkt(MemoryStream ms)
 {
     ms.Position = 4;
     ms.WriteInt((int)ms.Length - HeadLength);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Encrypts a value using the requested certificate.
        /// The certificate must have a valid RSA public key.
        /// </summary>
        /// <param name="value">The value to be encrypted.</param>
        /// <param name="certificate">The certificate used to encrypt the value.</param>
        /// <remarks> 
        /// First a cryptographically random AES key is generated.
        /// The value is encrypted using that AES key.
        /// The AES key is then encrypted using the RSA key from the certificate.
        /// Then the encrypted value is joined with the encrypted AES key.
        /// That result is base 64 encoded and returned.
        /// 
        /// The format of the result in binary (before base 64 encoding) is the following:
        /// [AES key length in bytes] - Length: 4 bytes
        /// [AES block size in bytes] - Length: 4 bytes
        /// [AES key encrypted length in bytes] - Length: 4 bytes
        /// [AES initialization vector encrypted length in bytes] - Length: 4 bytes
        /// [Certificate public key length in bytes] - Length: 4 bytes
        /// [Certificate public key] - Length: Public key length
        /// [Encrypted AES key] - Length: AES key encrypted length bytes
        /// [Encrypted AES initialization vector] - Length: AES Block size bytes
        /// [Encrypted value] - Length: remaining data length
        /// </remarks>
        /// <returns>The encrypted, base64-encoded value.</returns>
        public static string Encrypt(string value, X509Certificate2 certificate)
        {
            const int keySizeBits = 256;
            const int keySizeBytes = keySizeBits / 8;
            const int blockSizeBits = 128;
            const int blockSizeBytes = blockSizeBits / 8;

            // Get the RSA key from the certificate
            var rsa = certificate.PublicKey.Key as RSACryptoServiceProvider;
            if (rsa == null)
            {
                throw new InvalidOperationException("Certificate does not contain an RSA public key.");
            }

            // Get the public key as a byte array
            var publicKey = certificate.GetPublicKey();

            using (var aes = new AesManaged
            {
                KeySize = keySizeBits,
                BlockSize = blockSizeBits,
                Mode = CipherMode.CBC
            })
            {
                // Generate a cryptographically random initialization vector and key
                aes.GenerateIV();
                aes.GenerateKey();

                if (aes.IV.Length != blockSizeBytes)
                {
                    throw new InvalidOperationException("AES IV size is not equal to the block size.");
                }

                // Encrypt the AES key and initialization vector
                var keyBytes = rsa.Encrypt(aes.Key, false);
                var ivBytes = rsa.Encrypt(aes.IV, false);

                using (var memory = new MemoryStream())
                {
                    // Write the AES key length and block size
                    memory.WriteInt(keySizeBytes);
                    memory.WriteInt(blockSizeBytes);

                    // Write the sizes of the encrypted AES key and initialization vector
                    memory.WriteInt(keyBytes.Length);
                    memory.WriteInt(ivBytes.Length);

                    // Write the size of the certificate public key
                    memory.WriteInt(publicKey.Length);

                    // Write the public key
                    memory.Write(publicKey, 0, publicKey.Length);

                    // Write the encrypted AES key and initialization vector
                    memory.Write(keyBytes, 0, keyBytes.Length);
                    memory.Write(ivBytes, 0, ivBytes.Length);

                    // Encrypt and write the actual value using the aes encryption
                    using (var transform = aes.CreateEncryptor())
                    using (var crypto = new CryptoStream(memory, transform, CryptoStreamMode.Write))
                    {
                        var bytes = Encoding.UTF8.GetBytes(value);
                        crypto.Write(bytes, 0, bytes.Length);
                        crypto.FlushFinalBlock();
                    }

                    // Return the base 64 encoded result
                    return Convert.ToBase64String(memory.ToArray(), Base64FormattingOptions.InsertLineBreaks);
                }
            }
        }
Ejemplo n.º 8
0
        public void Receive_writes_new_bytes_from_deltaStream()
        {
            var deltaStream = new MemoryStream();
            deltaStream.WriteByte(DeltaStreamer.DeltaStreamConstants.NEW_BLOCK_START_MARKER);
            deltaStream.WriteInt(10); // Write 10 bytes
            for (int i = 0; i < 10; ++i) deltaStream.WriteByte((byte) (200 - i));
            deltaStream.Seek(0, SeekOrigin.Begin);

            var inputStream = new MemoryStream(); // empty
            var outputStream = new MemoryStream();

            var streamer = new DeltaStreamer();
            streamer.Receive(deltaStream, inputStream, outputStream);

            Assert.AreEqual(10, outputStream.Length);
            outputStream.GetBuffer().Take(10).SequenceEqual(deltaStream.GetBuffer().Skip(5).Take(10));
        }
Ejemplo n.º 9
0
Archivo: db.cs Proyecto: RSA-PM/RSA-PM
        public long SentMessage(string their_name, byte[] their_pubkey, string txt, byte[] myprv, byte[] msgid, byte[]replyTo)
        {
            if (replyTo == null)
                replyTo = new byte[16];
            long foundId = 0, prvId=0;
            foreach (var v in pubkeys)
            {
                if(their_pubkey.ArraysEqual(v.key))
                {
                    foundId=v.id;
                    break;
                }
            }
            if (myprv != null)
            {
                foreach (var v in prvkeys)
                {
                    if (myprv.ArraysEqual(v.key))
                    {
                        prvId = v.id;
                        break;
                    }
                }
                if (prvId == 0)
                    throw new Exception();
            }

            if (foundId == 0) { foundId = newpub(their_pubkey, their_name); }

            byte[] msgbuf;
            using (var ms = new MemoryStream())
            {
                ms.WriteInt((int)foundId);
                ms.WriteInt((int)prvId);
                ms.Write(msgid, 0, msgid.Length);
                ms.Write(replyTo, 0, replyTo.Length);
                var txtbuf = Encoding.UTF8.GetBytes(txt);
                ms.Write(txtbuf, 0, txtbuf.Length);
                ms.Flush();
                msgbuf = ms.ToArray();
            }

            var idq = conn.Query<long>("select id from outbox order by id desc limit 1",new{});
            long id = idq.Count() == 0 ? 1 : idq.First() + 1;
            var iv = ArrayrXor(outbox_iv, id);
            if (conn.Execute("insert into outbox(id, msg) select @id, @msg", new { id = id, msg = enc(msgbuf, iv) }) != 1)
                throw new Exception();
            return foundId;
        }