Ejemplo n.º 1
0
        public void EncryptAES(IWriteStream writeStream, string sharedSecret)
        {
            if (!IsEncrypt)
            {
                return;
            }
            using (var aesAlg = new RijndaelManaged()) {
                var key = new Rfc2898DeriveBytes(sharedSecret, _salt);
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                var byteFragment = writeStream.ToByteFragment();

                using (var resultStream = new MemoryStream()) {
                    using (var csEncrypt = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write)) {
                        csEncrypt.Write(byteFragment.Buffer, byteFragment.Offset, byteFragment.Count);
                    }

                    writeStream.Reset();
                    writeStream.ShiftLeft(aesAlg.IV);
                    var ivLength = (ushort)aesAlg.IV.Length;
                    writeStream.ShiftLeft(ivLength);
                    writeStream.ShiftRight((ushort)byteFragment.Count);
                    var bytes = resultStream.ToArray();
                    writeStream.ShiftRight(bytes);
                }
            }
        }