示例#1
0
        /// <summary>
        /// Creates a reference to a single-module assembly or a standalone module stored in memory
        /// from a hex-encoded byte stream representing a gzipped assembly image.
        /// </summary>
        /// <param name="image">
        /// A string containing a hex-encoded byte stream representing a gzipped assembly image.
        /// Hex digits are case-insensitive and can be separated by spaces or newlines.
        /// Cannot be null.
        /// </param>
        /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param>
        /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param>
        /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param>
        protected internal PortableExecutableReference CreateMetadataReferenceFromHexGZipImage(
            string image,
            MetadataReferenceProperties properties = default(MetadataReferenceProperties),
            DocumentationProvider documentation    = null,
            string filePath = null)
        {
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }

            using (var compressed = new MemoryStream(SoapHexBinary.Parse(image).Value))
                using (var gzipStream = new GZipStream(compressed, CompressionMode.Decompress))
                    using (var uncompressed = new MemoryStream())
                    {
                        gzipStream.CopyTo(uncompressed);
                        uncompressed.Position = 0;
                        return(MetadataReference.CreateFromStream(uncompressed, properties, documentation, filePath));
                    }
        }
示例#2
0
        public static GameEvent Deserialize(string content)
        {
            var bytes = SoapHexBinary.Parse(content).Value;

            var gameEvent = new GameEvent {
                Properties = new Dictionary <string, string>()
            };

            using (BinaryReader reader = new BinaryReader(new MemoryStream(bytes)))
            {
                var numProperties = reader.ReadInt32();

                for (int index = 0; index < numProperties; index++)
                {
                    gameEvent.Properties.Add(reader.ReadString(), reader.ReadString());
                }
            }

            return(gameEvent);
        }
示例#3
0
 public static Byte[] GetBytesFromHexString(string strInput)
 {
     Byte[] bytArOutput = new Byte[] { };
     if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0)
     {
         SoapHexBinary hexBinary = null;
         try
         {
             hexBinary = SoapHexBinary.Parse(strInput);
             if (hexBinary != null)
             {
                 bytArOutput = hexBinary.Value;
             }
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
         }
     }
     return(bytArOutput);
 }
示例#4
0
        public static object ConvertType(string sqlType, string val)
        {
            if (val == _nullValue)
            {
                return(DBNull.Value);
            }

            switch (sqlType.ToLower())
            {
            case "bit":
                //added for compatibility with bcp
                if (val == "0")
                {
                    val = "False";
                }
                if (val == "1")
                {
                    val = "True";
                }
                return(bool.Parse(val));

            case "datetime":
            case "smalldatetime":
                return(DateTime.Parse(val, CultureInfo.InvariantCulture));

            case "int":
                return(int.Parse(val));

            case "uniqueidentifier":
                return(new Guid(val));

            case "binary":
            case "varbinary":
            case "image":
                return(SoapHexBinary.Parse(val).Value);

            default:
                return(val);
            }
        }
示例#5
0
        //TODO ???
        public static byte[] GetBytesFromHexString(string strInput)
        {
            var bytArOutput = new byte[] { };

            if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0)
            {
                SoapHexBinary hexBinary = null;
                try
                {
                    hexBinary = SoapHexBinary.Parse(strInput);
                    if (hexBinary != null)
                    {
                        bytArOutput = hexBinary.Value;
                    }
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message);
                }
            }
            return(bytArOutput);
        }
示例#6
0
        public static void OpEncryption(Client c, PacketReader r)
        {
            byte[] aKey         = new byte[24];
            string sCharacterID = c.Account.info.UserId.ToString();

            for (int i = 0; i < sCharacterID.Length; i++)
            {
                aKey[i] = (byte)sCharacterID[i];
            }

            //Find a better way
            var    output    = new SoapHexBinary(SoapHexBinary.Parse(c.Account.Hwid1.ToString("X")).Value.Reverse().ToArray()).ToString();
            String machineID = "00000000" + output;
            int    count     = 0;

            for (int i = sCharacterID.Length; i < 16; i++)
            {
                aKey[i] = (byte)int.Parse(machineID.Substring(count, 2), NumberStyles.HexNumber);
                count  += 2;
            }

            Array.Copy(aKey, 0, aKey, 16, 8);
            int nBlockSize   = r.ReadInt();
            int bufferLength = r.ReadInt();

            byte[] aData = new byte[bufferLength];
            aData = r.ReadBytes(bufferLength);

            String sOpcode = TripleDESCipher.Decrypt(aData, aKey);

            int x = 0;

            for (int i = 0; i < 1156; i++)
            {
                int temp = Int32.Parse(sOpcode.Substring(x, 4));
                c.EncryptedHeaders[i] = (ushort)temp;
                x += 4;
            }
        }
示例#7
0
    public static void Main(string[] args)
    {
        //<snippet11>
        // Parse an XSD formatted string to create a SoapHexBinary object.
        string        xsdHexBinary = "3f789ABC";
        SoapHexBinary hexBinary    = SoapHexBinary.Parse(xsdHexBinary);

        //</snippet11>

        //<snippet12>
        // Print the value of the SoapHexBinary object in XSD format.
        Console.WriteLine("The SoapHexBinary object in XSD format is {0}.",
                          hexBinary.ToString());
        //</snippet12>

        //<snippet13>
        // Print the XSD type string of this particular SoapHexBinary object.
        Console.WriteLine(
            "The XSD type of the SoapHexBinary object is {0}.",
            hexBinary.GetXsdType());
        //</snippet13>

        //<snippet14>
        // Print the value of the SoapHexBinary object.
        Console.Write("hexBinary.Value contains:");
        for (int i = 0; i < hexBinary.Value.Length; ++i)
        {
            Console.Write(" " + hexBinary.Value[i]);
        }
        Console.WriteLine();
        //</snippet14>

        //<snippet16>
        // Print the XSD type string of the SoapHexBinary class.
        Console.WriteLine("The XSD type of the class SoapHexBinary is {0}.",
                          SoapHexBinary.XsdType);
        //</snippet16>
    }
示例#8
0
        private string GetSubjectKeyIdentifier()
        {
            if (!String.IsNullOrWhiteSpace(_certificateSubjectKeyIdentifier))
            {
                return(_certificateSubjectKeyIdentifier);
            }

            foreach (X509Extension extension in Certificate.Extensions)
            {
                if (!String.Equals(extension.Oid.FriendlyName, "Subject Key Identifier"))
                {
                    continue;
                }

                var           x509SubjectKeyIdentifierExtension = (X509SubjectKeyIdentifierExtension)extension;
                SoapHexBinary base64Binary = SoapHexBinary.Parse(x509SubjectKeyIdentifierExtension.SubjectKeyIdentifier);

                return(Convert.ToBase64String(base64Binary.Value));
            }

            throw new CryptographicException(
                      "No extension with the name 'Subject Key Identifier' was found in the certificate extensions");
        }
示例#9
0
        public static byte[] ToBytes(string packet, bool parse = true)
        {
            if (parse)
            {
                StringBuilder sr = new StringBuilder();

                foreach (char c in packet)
                {
                    if (IsHexChar(c))
                    {
                        sr.Append(c);
                    }
                    else if (c == '*')
                    {
                        sr.Append(sHexChars[sRandom.Next(0, 15)]);
                    }
                }

                packet = sr.ToString();
            }

            return(SoapHexBinary.Parse(packet).Value);
        }
示例#10
0
        public static Byte[] GetBytesFromHexString(string _Input)
        {
            string strInput = _Input.Replace(" ", "");

            Byte[] bytArOutput = new Byte[] { };
            if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0)
            {
                SoapHexBinary hexBinary = null;
                try
                {
                    hexBinary = SoapHexBinary.Parse(strInput);
                    if (hexBinary != null)
                    {
                        bytArOutput = hexBinary.Value;
                    }
                }
                catch (Exception ex)
                {
                    Ex.Show(ex.Info());
                }
            }
            return(bytArOutput);
        }
        private string DecodeCookie()
        {
            var cookieBytes        = SoapHexBinary.Parse(CookieValue).Value;
            var validationKeyBytes = SoapHexBinary.Parse(ValidationKey).Value;
            var decryptionKeyBytes = SoapHexBinary.Parse(DecryptionKey).Value;

            int signatureLength = 0;

            using (var validationAlgorithm = new HMACSHA1(validationKeyBytes))
            {
                signatureLength = validationAlgorithm.HashSize >> 3;
                if (cookieBytes.Length - 1 < signatureLength)
                {
                    return("The cookie cannot be validated. Validation signature hash size does not align with cookie length.");
                }

                var signature = validationAlgorithm.ComputeHash(cookieBytes, 0, cookieBytes.Length - signatureLength);
                for (int signatureIndex = 0; signatureIndex < signature.Length; signatureIndex++)
                {
                    // If we break early, we'll be more vulnerable to timing attacks.
                    if (signature[signatureIndex] != cookieBytes[cookieBytes.Length - signatureLength + signatureIndex])
                    {
                        return("Cookie signature validation failed.");
                    }
                }
            }

            int initializationVectorLength;
            var decryptedBytes = DecryptBytes(cookieBytes, decryptionKeyBytes, signatureLength, out initializationVectorLength);

            if (decryptedBytes.Length < 51 + initializationVectorLength)
            {
                return("Decrypted value is insufficient in length.");
            }

            return(DecodeCookieBytes(decryptedBytes, initializationVectorLength));
        }
示例#12
0
        public PwEntry GetEntryByUuid(string uuidHex)
        {
            var uuid = new PwUuid(SoapHexBinary.Parse(uuidHex).Value);

            return(GetAllEntries().SingleOrDefault(entry => entry.Uuid.Equals(uuid)));
        }
示例#13
0
        public RtpPacketTests()
        {
            var hex = SoapHexBinary.Parse(RTP_HEX);

            _packetBytes = hex.Value;
        }
示例#14
0
 /// <summary>
 /// Converts the Hash Hex String into a Byte[] for computational processing
 /// </summary>
 /// <param name="hashHexString">The Hash Hex String to convert back to bytes</param>
 /// <returns>Esentially reverses the HashToHexString function, turns the String back into Bytes</returns>
 public static Byte[] HashHexStringToBytes(String hashHexString)
 {
     return(SoapHexBinary.Parse(hashHexString).Value);
 }
示例#15
0
 public static byte[] GetByteArrayFromHexString(this string s)
 {
     return(SoapHexBinary.Parse(s).Value);
 }
示例#16
0
        private void kriptiranjeAes_Click(object sender, EventArgs e)
        {
            string TekstZaEnkripciju = originalTekstDatoteke.Text;
            string KljucZaEnkripciju = tekstZaAesKljuc.Text;

            if (TekstZaEnkripciju == null || TekstZaEnkripciju.Length <= 0)
            {
                MessageBox.Show("Tekst za enkripciju neispravan");
                return;
            }

            if (KljucZaEnkripciju == null || KljucZaEnkripciju.Length <= 0)
            {
                MessageBox.Show("Ključ za enkripciju neispravan");
                return;
            }

            try
            {
                byte[]        encryptedData;
                SoapHexBinary soapHexBinary = SoapHexBinary.Parse(KljucZaEnkripciju);
                byte[]        Key           = soapHexBinary.Value;
                byte[]        IV            = System.Text.ASCIIEncoding.ASCII.GetBytes("16A7C51F5CA8F123");
                using (Aes aesAlgoritam = Aes.Create())
                {
                    aesAlgoritam.Key = Key;
                    aesAlgoritam.IV  = IV;
                    ICryptoTransform encryptor = aesAlgoritam.CreateEncryptor(aesAlgoritam.Key, aesAlgoritam.IV);
                    using (MemoryStream memoryStreamEncrypt = new MemoryStream())
                    {
                        using (CryptoStream cryptoStreamEncrypt = new CryptoStream(memoryStreamEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (StreamWriter streamWriterEncrypt = new StreamWriter(cryptoStreamEncrypt))
                            {
                                streamWriterEncrypt.Write(TekstZaEnkripciju);
                            }
                            encryptedData = memoryStreamEncrypt.ToArray();
                        }
                    }
                }
                kriptiraniTekstDatoteke.Text = Convert.ToBase64String(encryptedData);
            }

            catch (Exception)
            {
                MessageBox.Show("Enkripcija neuspjela! Provjerite ispravnost ključa i originalni tekst");
                return;
            }

            string podaci   = "";
            string dokument = "";

            System.Windows.Forms.SaveFileDialog dijalogZaUcitavanje = new System.Windows.Forms.SaveFileDialog();
            dijalogZaUcitavanje.Filter     = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            dijalogZaUcitavanje.DefaultExt = "txt";
            dijalogZaUcitavanje.ShowDialog();
            if (dijalogZaUcitavanje.FileName != "")
            {
                podaci   = kriptiraniTekstDatoteke.Text;
                dokument = dijalogZaUcitavanje.FileName;
                File.WriteAllText(dokument, podaci);
            }
            else
            {
                MessageBox.Show("Molimo odredite gdje želite da se kriptirani tekst spremi!");
            }
        }
示例#17
0
        public void Parse_Value_Invalid()
        {
            string        xsdHexBinary;
            SoapHexBinary shb;

            xsdHexBinary = "3f789ABG";
#if NET_2_0
            try {
                SoapHexBinary.Parse(xsdHexBinary);
                Assert.Fail("#A1");
            } catch (RemotingException ex) {
                // Soap Parse error, xsd:type xsd:hexBinary
                // invalid 3f789ABCZ
                Assert.AreEqual(typeof(RemotingException), ex.GetType(), "#A2");
                Assert.IsNull(ex.InnerException, "#A3");
                Assert.IsNotNull(ex.Message, "#A4");
                Assert.IsTrue(ex.Message.IndexOf("xsd:hexBinary") != -1, "#A5");
                Assert.IsTrue(ex.Message.IndexOf(xsdHexBinary) != -1, "#A6");
            }
#else
            shb = SoapHexBinary.Parse(xsdHexBinary);
            Assert.AreEqual("hexBinary", shb.GetXsdType(), "#A1");
            Assert.AreEqual("3F789AB0", shb.ToString(), "#A2");
            Assert.AreEqual(new byte [] { 63, 120, 154, 176 }, shb.Value, "#A3");
#endif

            xsdHexBinary = "3f789AbCE";
            try {
                shb = SoapHexBinary.Parse(xsdHexBinary);
                Assert.Fail("#B1");
            } catch (RemotingException ex) {
                // Soap Parse error, xsd:type xsd:hexBinary
                // invalid 3f789AbCE
                Assert.AreEqual(typeof(RemotingException), ex.GetType(), "#B2");
                Assert.IsNull(ex.InnerException, "#B3");
                Assert.IsNotNull(ex.Message, "#B4");
                Assert.IsTrue(ex.Message.IndexOf("xsd:hexBinary") != -1, "#B5");
                Assert.IsTrue(ex.Message.IndexOf(xsdHexBinary) != -1, "#B6");
            }

            xsdHexBinary = "3f789GbC";
#if NET_2_0
            try {
                shb = SoapHexBinary.Parse(xsdHexBinary);
                Assert.Fail("#C1");
            } catch (RemotingException ex) {
                // Soap Parse error, xsd:type xsd:hexBinary
                // invalid 3f789GbC
                Assert.AreEqual(typeof(RemotingException), ex.GetType(), "#C2");
                Assert.IsNull(ex.InnerException, "#C3");
                Assert.IsNotNull(ex.Message, "#C4");
                Assert.IsTrue(ex.Message.IndexOf("xsd:hexBinary") != -1, "#C5");
                Assert.IsTrue(ex.Message.IndexOf(xsdHexBinary) != -1, "#C6");
            }
#else
            shb = SoapHexBinary.Parse(xsdHexBinary);
            Assert.AreEqual("hexBinary", shb.GetXsdType(), "#C1");
            Assert.AreEqual("3F7890BC", shb.ToString(), "#C2");
            Assert.AreEqual(new byte [] { 63, 120, 144, 188 }, shb.Value, "#C3");
#endif

            xsdHexBinary = "3f-89ABC";
#if NET_2_0
            try {
                shb = SoapHexBinary.Parse(xsdHexBinary);
                Assert.Fail("#D1");
            } catch (RemotingException ex) {
                // Soap Parse error, xsd:type xsd:hexBinary
                // invalid 3f-89ABC
                Assert.AreEqual(typeof(RemotingException), ex.GetType(), "#D2");
                Assert.IsNull(ex.InnerException, "#D3");
                Assert.IsNotNull(ex.Message, "#D4");
                Assert.IsTrue(ex.Message.IndexOf("xsd:hexBinary") != -1, "#D5");
                Assert.IsTrue(ex.Message.IndexOf(xsdHexBinary) != -1, "#D6");
            }
#else
            shb = SoapHexBinary.Parse(xsdHexBinary);
            Assert.AreEqual("hexBinary", shb.GetXsdType(), "#D1");
            Assert.AreEqual("3F089ABC", shb.ToString(), "#D2");
            Assert.AreEqual(new byte [] { 63, 8, 154, 188 }, shb.Value, "#D3");
#endif
        }
 public static byte[] ToBinary(this string hexString)
 {
     byte[] binary = SoapHexBinary.Parse(hexString).Value;
     Array.Reverse(binary);
     return(binary);
 }
示例#19
0
        public async Task <IHttpActionResult> ReceiveHook(string type, long id)
        {
            if (!IsRequestFromGitHub())
            {
                Log.Info($"Rejecting webhook request from impersonator: {GetIPAddress()} {Request.RequestUri}");
                return(BadRequest("Not you."));
            }

            // Invalid inputs can make these fail. That's ok.
            var eventName  = Request.ParseHeader(EventHeaderName, x => x);
            var deliveryId = Request.ParseHeader(DeliveryIdHeaderName, x => Guid.Parse(x));

            // signature of the form "sha1=..."
            var signature = Request.ParseHeader(SignatureHeaderName, x => SoapHexBinary.Parse(x.Substring(5)).Value);

            using (var context = new ShipHubContext()) {
                Hook hook;
                if (type == "org")
                {
                    hook = await context.Hooks.AsNoTracking().SingleOrDefaultAsync(x => x.OrganizationId == id);
                }
                else
                {
                    hook = await context.Hooks.AsNoTracking().SingleOrDefaultAsync(x => x.RepositoryId == id);
                }

                if (hook == null)
                {
                    // I don't care anymore. This is GitHub's problem.
                    // They should support unsubscribing from a hook with a special response code or body.
                    // We may not even have credentials to remove the hook anymore.
                    return(NotFound());
                }

                var secret            = Encoding.UTF8.GetBytes(hook.Secret.ToString());
                var webhookEventActor = await _grainFactory.GetGrain <IWebhookEventActor>(0); // Stateless worker grain with single pool (0)

                var debugInfo = $"[{type}:{id}#{eventName}/{deliveryId}]";

                Task hookTask = null;
                switch (eventName)
                {
                case "commit_comment": {
                    var payload = await ReadPayloadAsync <CommitCommentPayload>(signature, secret);

                    hookTask = webhookEventActor.CommitComment(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "issue_comment": {
                    var payload = await ReadPayloadAsync <IssueCommentPayload>(signature, secret);

                    hookTask = webhookEventActor.IssueComment(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "issues": {
                    var payload = await ReadPayloadAsync <IssuesPayload>(signature, secret);

                    hookTask = webhookEventActor.Issues(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "label": {
                    var payload = await ReadPayloadAsync <LabelPayload>(signature, secret);

                    hookTask = webhookEventActor.Label(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "milestone": {
                    var payload = await ReadPayloadAsync <MilestonePayload>(signature, secret);

                    hookTask = webhookEventActor.Milestone(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "ping":
                    await ReadPayloadAsync <object>(signature, secret); // read payload to validate signature

                    break;

                case "pull_request_review_comment": {
                    var payload = await ReadPayloadAsync <PullRequestReviewCommentPayload>(signature, secret);

                    hookTask = webhookEventActor.PullRequestReviewComment(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "pull_request_review": {
                    var payload = await ReadPayloadAsync <PullRequestReviewPayload>(signature, secret);

                    hookTask = webhookEventActor.PullRequestReview(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "pull_request": {
                    var payload = await ReadPayloadAsync <PullRequestPayload>(signature, secret);

                    hookTask = webhookEventActor.PullRequest(DateTimeOffset.UtcNow, payload);
                }
                break;

                case "push": {
                    var payload = await ReadPayloadAsync <PushPayload>(signature, secret);

                    hookTask = webhookEventActor.Push(DateTimeOffset.UtcNow, payload);
                    break;
                }

                case "repository": {
                    var payload = await ReadPayloadAsync <RepositoryPayload>(signature, secret);

                    hookTask = webhookEventActor.Repository(DateTimeOffset.UtcNow, payload);
                    break;
                }

                case "status": {
                    var payload = await ReadPayloadAsync <StatusPayload>(signature, secret);

                    hookTask = webhookEventActor.Status(DateTimeOffset.UtcNow, payload);
                    break;
                }

                default:
                    Log.Error($"Webhook event '{eventName}' is not handled. Either support it or don't subscribe to it.");
                    break;
                }

                // Just in case
                if (hookTask == null && eventName != "ping")
                {
                    Log.Error($"Webhook event '{eventName}' does net set the {nameof(hookTask)}. Failures will be silent.");
                }

                hookTask?.LogFailure(debugInfo);

                // Reset the ping count so this webhook won't get reaped.
                await context.BulkUpdateHooks(seen : new[] { hook.Id });
            }

            return(StatusCode(HttpStatusCode.Accepted));
        }
示例#20
0
        /// <summary>
        /// Decrypt the given string.  Assumes the string was encrypted using
        /// EncryptStringAES(), using an identical sharedSecret.
        /// </summary>
        /// <param name="cipherText">The text to decrypt.</param>
        /// <param name="sharedSecret">A password used to generate a key for decryption.</param>
        public string DecryptStringAES(string cipherText, string sharedSecret, string inpSalt = null, int FromFETPIP = 0)
        {
            if (string.IsNullOrEmpty(cipherText))
            {
                throw new ArgumentNullException("cipherText");
            }
            if (string.IsNullOrEmpty(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }
            if (!string.IsNullOrEmpty(inpSalt))
            {
                //System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                //salt = encoding.GetBytes(inpSalt);

                // UNCOMMENT ME (below)
                salt = Encoding.ASCII.GetBytes(inpSalt + pepperEnc);
                //salt = Encoding.ASCII.GetBytes(inpSalt);
            }

            // Declare the RijndaelManaged object
            // used to decrypt the data.
            RijndaelManaged aesAlg = null;

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            try
            {
                // generate the key from the shared secret and the salt
                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, salt);

                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg           = new RijndaelManaged();
                aesAlg.Padding   = PaddingMode.Zeros;
                aesAlg.BlockSize = 256;
                aesAlg.KeySize   = 256;
                aesAlg.Key       = key.GetBytes(aesAlg.KeySize / 8);
                aesAlg.IV        = key.GetBytes(aesAlg.BlockSize / 8);

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
                // Create the streams used for decryption.
                if (FromFETPIP == 1)
                {
                    byte[] bytes = Convert.FromBase64String(cipherText);
                    using (MemoryStream msDecrypt = new MemoryStream(bytes))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
                else
                {
                    SoapHexBinary shb   = SoapHexBinary.Parse(cipherText);
                    byte[]        bytes = shb.Value;

                    using (MemoryStream msDecrypt = new MemoryStream(bytes))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            using (StreamReader srDecrypt = new StreamReader(csDecrypt))

                                // Read the decrypted bytes from the decrypting stream
                                // and place them in a string.
                                plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            finally
            {
                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                {
                    aesAlg.Clear();
                }
            }

            return(plaintext.TrimEnd('\0'));  //  TrimEnd shouldn't be necessary but sometimes they're still there (it also gets stripped when inserted into dictionary in LogggedInMaster)
        }
示例#21
0
        public static int Unlock(string filePath, bool overWrite, bool unlockVBA, IProgress <int> progress, IProgress <int> consoleProg)
        {
            // Initial variable declarations
            string homeDirectory     = "";
            string hopefulNewName    = "";
            int    currentProgress   = 0;
            int    worksheetProgress = 0;

            // Gets the filename from the provided file path
            string fileName = Path.GetFileName(filePath);

            // Creates what we hope will be the new name of the file
            if (overWrite)
            {
                hopefulNewName = fileName;
            }
            else
            {
                hopefulNewName = "unlocked_" + fileName;
            }

            // Saves the home directory to a string
            homeDirectory = Path.GetDirectoryName(filePath);


            // Creates a GUID for the temporary directory, and creates C:\Temp\... filepath
            string directoryID   = Guid.NewGuid().ToString();
            string directoryPath = "C:\\Temp\\" + directoryID;

            currentProgress += 5;
            progress.Report(currentProgress);


            // Gets the file extension from the filename
            string fileExtension = Path.GetExtension(filePath);


            // Uses the C:\Temp\... path from earlier, and makes the working directory
            Directory.CreateDirectory(directoryPath);
            currentProgress += 5;
            progress.Report(currentProgress);

            // Copies the workbook to the working directory as a .zip
            File.Copy(filePath, directoryPath + "\\workBook.zip");
            currentProgress += 5;
            progress.Report(currentProgress);

            // Extracts the .zip contents
            ZipFile.ExtractToDirectory(directoryPath + "\\workBook.zip", directoryPath + "\\workBook");
            currentProgress += 5;
            progress.Report(currentProgress);

            if (unlockVBA)
            {
                if (File.Exists(directoryPath + "\\workBook\\xl\\vbaProject.bin"))
                {
                    try {
                        // Reads vbaProject.bin
                        byte[] buf = File.ReadAllBytes(directoryPath + "\\workBook\\xl\\vbaProject.bin");

                        // Encodes the binary as hex, which allows us to edit the three hex couplets below
                        var str = new SoapHexBinary(buf).ToString();


                        // Find the VBA protection key ("DPB") and replaces it with a nothing key ("DBx")
                        // This causes the VBA editor to go through recovery and delete protection
                        str = str.Replace("445042", "444278");

                        // Writes the hex back to binary into the vbaProject.bin file
                        File.WriteAllBytes(directoryPath + "\\workBook\\xl\\vbaProject.bin", SoapHexBinary.Parse(str).Value);
                    }
                    catch {
                        return(2);
                    }
                }
            }
            currentProgress += 10;
            progress.Report(currentProgress);

            // Searches in the decompiled workbook's xl directory for worksheets, and
            string[] worksheets = Directory.GetFiles(directoryPath + "\\workBook\\xl\\worksheets");

            worksheetProgress = 50 / worksheets.Length;

            // Calls the RemoveSheetProtection method for each of them
            foreach (string worksheet in worksheets)
            {
                RemoveSheetProtection(worksheet);
                currentProgress += worksheetProgress;
                progress.Report(currentProgress);
            }

            // Recompiles the workbook with the newly unprotected sheets
            ZipFile.CreateFromDirectory(directoryPath + "\\workBook", directoryPath + "\\Book1Mod.zip");
            currentProgress += 10;
            progress.Report(currentProgress);

            // Copies the .zip back as an Excel workbook to the home directory
            try {
                File.Copy(directoryPath + "\\Book1Mod.zip", homeDirectory + "\\" + hopefulNewName, overWrite);
                progress.Report(100);
                consoleProg.Report(0);
            }
            catch {
                Directory.Delete(directoryPath, true);
                progress.Report(100);
                consoleProg.Report(1);
                return(1);
            }


            // Deletes the C:\Temp\... directory.
            Directory.Delete(directoryPath, true);

            return(0);
        }
示例#22
0
        internal static object SoapCoerceArg(object value, Type pt, Hashtable keyToNamespaceTable)
        {
            object obj = null;

            if (value != null)
            {
                try
                {
                    if (pt.IsByRef)
                    {
                        pt = pt.GetElementType();
                    }
                    if (pt.IsInstanceOfType(value))
                    {
                        obj = value;
                    }
                    else
                    {
                        string text = value as string;
                        if (text != null)
                        {
                            if (pt == typeof(double))
                            {
                                if (text == "INF")
                                {
                                    obj = double.PositiveInfinity;
                                }
                                else if (text == "-INF")
                                {
                                    obj = double.NegativeInfinity;
                                }
                                else
                                {
                                    obj = double.Parse(text, CultureInfo.InvariantCulture);
                                }
                            }
                            else if (pt == typeof(float))
                            {
                                if (text == "INF")
                                {
                                    obj = float.PositiveInfinity;
                                }
                                else if (text == "-INF")
                                {
                                    obj = float.NegativeInfinity;
                                }
                                else
                                {
                                    obj = float.Parse(text, CultureInfo.InvariantCulture);
                                }
                            }
                            else if (SoapType.typeofISoapXsd.IsAssignableFrom(pt))
                            {
                                if (pt == SoapType.typeofSoapTime)
                                {
                                    obj = SoapTime.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapDate)
                                {
                                    obj = SoapDate.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapYearMonth)
                                {
                                    obj = SoapYearMonth.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapYear)
                                {
                                    obj = SoapYear.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapMonthDay)
                                {
                                    obj = SoapMonthDay.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapDay)
                                {
                                    obj = SoapDay.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapMonth)
                                {
                                    obj = SoapMonth.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapHexBinary)
                                {
                                    obj = SoapHexBinary.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapBase64Binary)
                                {
                                    obj = SoapBase64Binary.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapInteger)
                                {
                                    obj = SoapInteger.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapPositiveInteger)
                                {
                                    obj = SoapPositiveInteger.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNonPositiveInteger)
                                {
                                    obj = SoapNonPositiveInteger.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNonNegativeInteger)
                                {
                                    obj = SoapNonNegativeInteger.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNegativeInteger)
                                {
                                    obj = SoapNegativeInteger.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapAnyUri)
                                {
                                    obj = SoapAnyUri.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapQName)
                                {
                                    obj = SoapQName.Parse(text);
                                    SoapQName soapQName = (SoapQName)obj;
                                    if (soapQName.Key.Length == 0)
                                    {
                                        soapQName.Namespace = (string)keyToNamespaceTable["xmlns"];
                                    }
                                    else
                                    {
                                        soapQName.Namespace = (string)keyToNamespaceTable["xmlns:" + soapQName.Key];
                                    }
                                }
                                else if (pt == SoapType.typeofSoapNotation)
                                {
                                    obj = SoapNotation.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNormalizedString)
                                {
                                    obj = SoapNormalizedString.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapToken)
                                {
                                    obj = SoapToken.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapLanguage)
                                {
                                    obj = SoapLanguage.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapName)
                                {
                                    obj = SoapName.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapIdrefs)
                                {
                                    obj = SoapIdrefs.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapEntities)
                                {
                                    obj = SoapEntities.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNmtoken)
                                {
                                    obj = SoapNmtoken.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNmtokens)
                                {
                                    obj = SoapNmtokens.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapNcName)
                                {
                                    obj = SoapNcName.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapId)
                                {
                                    obj = SoapId.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapIdref)
                                {
                                    obj = SoapIdref.Parse(text);
                                }
                                else if (pt == SoapType.typeofSoapEntity)
                                {
                                    obj = SoapEntity.Parse(text);
                                }
                            }
                            else if (pt == typeof(bool))
                            {
                                if (text == "1" || text == "true")
                                {
                                    obj = true;
                                }
                                else
                                {
                                    if (!(text == "0") && !(text == "false"))
                                    {
                                        throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Message_CoercionFailed"), text, pt));
                                    }
                                    obj = false;
                                }
                            }
                            else if (pt == typeof(DateTime))
                            {
                                obj = SoapDateTime.Parse(text);
                            }
                            else if (pt.IsPrimitive)
                            {
                                obj = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture);
                            }
                            else if (pt == typeof(TimeSpan))
                            {
                                obj = SoapDuration.Parse(text);
                            }
                            else if (pt == typeof(char))
                            {
                                obj = text[0];
                            }
                            else
                            {
                                obj = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture);
                            }
                        }
                        else
                        {
                            obj = Convert.ChangeType(value, pt, CultureInfo.InvariantCulture);
                        }
                    }
                }
                catch (Exception)
                {
                }
                if (obj == null)
                {
                    string arg;
                    if (RemotingServices.IsTransparentProxy(value))
                    {
                        arg = typeof(MarshalByRefObject).ToString();
                    }
                    else
                    {
                        arg = value.ToString();
                    }
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Message_CoercionFailed"), arg, pt));
                }
            }
            return(obj);
        }
示例#23
0
 public static byte[] HexStringToBytes(this string str)
 {
     return(SoapHexBinary.Parse(str).Value);
 }
示例#24
0
 /// <summary>
 /// Convert a hexadecimal string to bytes.
 /// </summary>
 public static byte[] GetStringToBytes(string value) => SoapHexBinary.Parse(value).Value;
示例#25
0
    public static byte[] ToBytes(string hex)
    {
        var shb = SoapHexBinary.Parse(hex);

        return(shb.Value);
    }
示例#26
0
        public void TestDecrytp()
        {
            //for (int i = 0; i < 10000; i++)
            {
                ECDiffieHellmanCng bob = new ECDiffieHellmanCng
                {
                    KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash,
                    HashAlgorithm         = CngAlgorithm.Rsa
                };

                string clientPubKeyString  = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEDEKneqEvcqUqqFMM1HM1A4zWjJC+I8Y+aKzG5dl+6wNOHHQ4NmG2PEXRJYhujyodFH+wO0dEr4GM1WoaWog8xsYQ6mQJAC0eVpBM96spUB1eMN56+BwlJ4H3Qx4TAvAs";
                var    clientPublicKeyBlob = Base64Url.Decode(clientPubKeyString);

                //GetCryptoServiceProvider(clientPublicKeyBlob);


                //clientPublicKeyBlob = FixPublicKey(clientPublicKeyBlob);

                Assert.AreEqual(120, clientPublicKeyBlob.Length);

                //var clientPubKey = ECDiffieHellmanCngPublicKey.FromByteArray(clientPublicKeyBlob, CngKeyBlobFormat.EccPublicBlob);

                //string serverSecKeyString = "MB8CAQAwEAYHKoZIzj0CAQYFK4EEACIECDAGAgEBBAEB";
                //var serverSecKeyBlob = Base64Url.Decode(serverSecKeyString);
                //serverSecKeyBlob = FixPublicKey(serverSecKeyBlob);
                //Assert.AreEqual(40, serverSecKeyBlob.Length);
                //var serverPrivKey = ECDiffieHellmanCngPublicKey.FromByteArray(serverSecKeyBlob, CngKeyBlobFormat.Pkcs8PrivateBlob);


                //byte[] bobKey = bob.DeriveKeyMaterial(bob.PublicKey);

                using (RijndaelManaged rijAlg = new RijndaelManaged())
                {
                    rijAlg.BlockSize    = 128;
                    rijAlg.Padding      = PaddingMode.None;
                    rijAlg.Mode         = CipherMode.CFB;
                    rijAlg.FeedbackSize = 8;

                    rijAlg.Key = Base64Url.Decode("ZOBpyzki/M8UZv5tiBih048eYOBVPkQE3r5Fl0gmUP4=");
                    rijAlg.IV  = Base64Url.Decode("ZOBpyzki/M8UZv5tiBih0w==");

                    Assert.AreEqual(32, rijAlg.Key.Length);

                    Assert.AreEqual(rijAlg.Key.Take(16).ToArray(), rijAlg.IV);

                    // Create a decrytor to perform the stream transform.
                    ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                    // Create the streams used for decryption.
                    using (MemoryStream msDecrypt = new MemoryStream())
                    {
                        byte[] buffer1 = SoapHexBinary.Parse("4B4FCA0C2A4114155D67F8092154AAA5EF").Value;
                        byte[] buffer2 = SoapHexBinary.Parse("DF53B9764DB48252FA1AE3AEE4").Value;
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Position = 0;
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] result1 = new byte[17];
                            csDecrypt.Read(result1, 0, 17);

                            msDecrypt.Position = 0;
                            msDecrypt.SetLength(0);
                            ;

                            msDecrypt.Write(buffer2, 0, buffer2.Length);
                            msDecrypt.Position = 0;

                            byte[] result2 = new byte[13];
                            csDecrypt.Read(result2, 0, 13);

                            Assert.AreEqual(SoapHexBinary.Parse("0400000000499602D2FC2FCB233F34D5DD").Value, result1);
                            Assert.AreEqual(SoapHexBinary.Parse("3C000000085A446D11C0C7AA5A").Value, result2);


                            // Hashing
                            MemoryStream hashStream = new MemoryStream();
                            Assert.True(BitConverter.IsLittleEndian);
                            hashStream.Write(BitConverter.GetBytes(1L), 0, 8);
                            byte[] text = SoapHexBinary.Parse("3C00000008").Value;
                            hashStream.Write(text, 0, text.Length);
                            hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);

                            SHA256Managed crypt  = new SHA256Managed();
                            var           buffer = hashStream.ToArray();
                            byte[]        crypto = crypt.ComputeHash(buffer, 0, buffer.Length).Take(8).ToArray();
                            Assert.AreEqual(SoapHexBinary.Parse("5A446D11C0C7AA5A").Value, crypto);
                        }
                    }
                    using (MemoryStream msDecrypt = new MemoryStream())
                    {
                        byte[] buffer1 = SoapHexBinary.Parse("4B4FCA0C2A4114155D67F8092154AAA5EF").Value;
                        byte[] buffer2 = SoapHexBinary.Parse("DF53B9764DB48252FA1AE3AEE4").Value;
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Write(buffer2, 0, buffer2.Length);
                        msDecrypt.Position = 0;
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            byte[] result1 = new byte[buffer1.Length];
                            csDecrypt.Read(result1, 0, result1.Length);

                            byte[] result2 = new byte[13];
                            csDecrypt.Read(result2, 0, 13);

                            Assert.AreEqual(SoapHexBinary.Parse("0400000000499602D2FC2FCB233F34D5DD").Value, result1);
                            Assert.AreEqual(SoapHexBinary.Parse("3C000000085A446D11C0C7AA5A").Value, result2);


                            // Hashing
                            MemoryStream hashStream = new MemoryStream();
                            Assert.True(BitConverter.IsLittleEndian);
                            hashStream.Write(BitConverter.GetBytes(1L), 0, 8);
                            byte[] text = SoapHexBinary.Parse("3C00000008").Value;
                            hashStream.Write(text, 0, text.Length);
                            hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);

                            SHA256Managed crypt  = new SHA256Managed();
                            var           buffer = hashStream.ToArray();
                            byte[]        crypto = crypt.ComputeHash(buffer, 0, buffer.Length).Take(8).ToArray();
                            Assert.AreEqual(SoapHexBinary.Parse("5A446D11C0C7AA5A").Value, crypto);
                        }
                    }
                }
            }
        }
示例#27
0
        public void LabTest()
        {
            // x = 8, z = 9
            string test  = "78daedcdc109c0200004c1233e125bb32f1b4a836a170acec0bef74b52576f294f36f2f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f73fe10f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002718974bff9ba43b9b1d578f30";
            string test2 = "789ced5dc9721cc711ed8e09c5486341185877872f085c110179df480220099120294ba47ce4cd115ee99dd64aefa6f7332fd09d3cf80374d00f38829f40ff8088b32f7067cfd44cf774d792f5b23bd14065c470d033fdea655657d6cbaa6e80af6459f6bf939393f1789c57acf8340fb6a3a3a39733d0e6fc930991133d833f17e1cfc7444f0ecc3ee93ffe71959f15be007f3eeffff202f0f865fabf320099f422fc4533c6017ef862e33f8a5f26fe053f9b5ee8fa03e10b8f3fae29f34b8f3f1dfe687ac9f94f317e881f76405dfff3790130e3ee9f7fbcd0bfd907e1f452f3ef78c63fc9caf8fbe65fc43fe130cfe9cfc4fc5b51400dfee8f2435d7fb5f9e5eb2f6ef8eaf3ff19e08fa63f23f143f59f80fee7d50a28eb5f7fabf31f73052837fee6facfe0968bdf6c40b0f985d6bf950d0085f8e76d45d0abafbf64f54fe9fa2ff29ff835f47fd15a04bd74fdc1e3971a7fb1035078fe55e257d75f845f447f117ed401b3fe9e5ba6a0ff739b1075fffbdfcb05302bf64ef879f4a2fb5f31fa2fa93f547ff1e985f557833f371ea88dbf65fc4af5472cbfdcfdb799a95cff61eb9f363faebfd8febf84feeaf2afeefff3f8a5f59f1bff19e05f14006c7ed1f9577dfd3d61872fbbfe52ebff45fcbafaa3a5bfa635edfa8b6fa760ff577bfd2f7dffb97f7e75fd8da69ff1830ee8afffb5d75faef9d7ed91ecfaa3853f73778974fccdf07be07726602ffcb9895f5d7f99fc67abfee01bf17f1ee5cf21fd3d03fa87e93fbefe8db7230101c4f517f300ad3f9e3c295e474f80f8eb1e54e680f27b0fbfe8fcb7d2bc8f5e7cfdc976a0077e9703d2fad720f0f00b3fffd5b45ee3b738d039bfcb016d7e8f75b1fe9d4e19f4eaf587bafe4becff02fb1ff8fa934fbf182122facb0fbec63fd7df680146fbdff0c73ae0609f9de07640f6f9eb167e4f0708d4ffc65aeb8feee3cfedeb3faf0392f3efc4a2ffddf32ff63fb8fc92cf1fb65b0ffc3efdefbaff1bebdfaafebae93be167e8bfc40540f7bf859fbfeadd01b0fe13d87f666f40b4e92f107f04ffb4c11fafbf31f5471b7fa40b8eeb3f3bc1e549b7f35f4ffcd6eb9f791d90dc7f6dd15f1fbfe8fd476dfd8fe0efe3fe431ffa6b77a097f8eb365dd1ffbefbbfaeffbefd8fe1afbfa3d9651c80e347f7df65f6bf91f5377fffa15d7fa3f945ea8f2771559067f2e9a1fe57e6470a90b3a0bfb983bf870d7867fc9e0e10baff99c7f24bdc80aed47f2d0499d38191ccf347e6fed3ec6dda2800acfc42cf3fadee3f04172002dbbf3efd73d18bdd7f8d3611fd2bda595f8fa5175aff0af047eb9fbdff7d5b510dfe080f5c97dfc6df76ff61c67f741411bf53ff3c1d2052ffbb1cf0f0775cff7b1c90d43f1b7fc70b2070ff5beef75f22f557ecf9db56fe00fdc3ef7f2af393030715feeaac9305f0c3cf5fadd43f3c7e587f97e38fdbfd65fdb59c7f63e31f3bea3ffffe4787fbbf5e13d1df72fbb5b500f1de0912d25f5b0f4cf9fa7fc4f6c0a9ffecf84b63f263f5a7e6fe9b8cfee93e00a4fefb1f1e077cf58fc4f33ff3fdff567a3277fca8fe78eb0fab0372fc07083fbafe1dfbf4bf537e7ffd67e31fc9ac3ffdfc96f04775fd8fd5dfdcc36f61cf57eb8fb85d007ffd69e7175dff36f923f43f427f4d6366fe595b83f8b91eacaeffd6d6960ef8cca2ffac6180fcfd2919fdd3d65fdd07803cfcdefa5f60fde5e02f4ff13980ea9ff71650d7fa375f8069f1cf1a73ecffdb1c381270a0f2fc85167ff5fecf68340aeeffbafec7df7fa5b60e2625ffa895bf9dbec11fbdff3cce677fffab3d7e0b7b1b7f94fe9af27ba6bf35fa7cddc5dfa63f6c0766fcebeb9386fe97f2cbe58fd1dfbc1a7fbe22bf7c7ebefe56f9fdfabf2c4bacfc8c2d0044fe2af79f587dbe127f34bdd0fd2ff70d0037bddcfac342ef73406cffd1caef70416efe75f33bf4e714f147afff7c8fe074cb5f63afcb0f8f3ffefeeb41b9ff50fcdbaebfaefa4b40ff2afa3b5a71c049dfa2bfb1fa67fefe675bfc16f676fe88f56f957fb5fec85f7238d0ca1fa3bfe38afe33f865f437afe96f117f4d7e1bfcebeb01facb7060b5fe28f86b0e34e20fe167dc0370de7ff7589d9fd1e92df1b75bd608dfce1f39ff7be49fc11f3bff47dfff179a7ffdfadfe5fcefed7fbb030dfe98fd4fe7affff4c01f547f04f203ebbf7ca6c298fe47de7f2d1b2bf71f2cfa1fcc1f7fff3542ffdbe75fa603e3e5ffbfd1a2ffa43f36769bfef23c30f3bf9cfe73d7bfd5fe67f10be9ef32fe207e71fd5dad3f6a2ef4c06fedde9cb7feece2f91337bf8cfec5c72f34ff47ff0a840cbf2f7ebb07c2fae3e0ef52ff42e20fe58f58ff39cbef1ef89d05681ffcb5df7f85f5ff88fdfc53ee5affe6ae2d4011fd5dfeff1badfc0bf2e9b4b1312ca3bf35fe95fdff4afd315ddd1997dd7f6eeeff1bfe08fde7e96f3eef80f24da4fe88d0ff257fad0088e567ff1e40bb6d6c60f8298847f9b5fdd78effbcfbaf3d7ef4f1b9ffa44ef931fc791fbf43c76b8f9f84d7cd7fedf13374fea1e3b5fb4f3fff503c9abf9803faf1ebe2cffbf83beff10f3f7fcf77fe6beb9f365ebbff878f47f3573dff2107f4fb3fe1111bfefc31f8fc831ad8001bf8efa7d9e7a6103f00ce86af7fdafc91f8db5278fdf8d5f317d4cf5ef27707c45b4d3b7f078a17cbbf38fcaddb2fcc7f8af31fc1eface0b9e953c7b3b367bb4c85cafc85e52f8a47f32fe53f8657d27f9dfcdd7eb581e7f19bb18ee0b757f09cf4294ede46f2bf89e7e5ef34cf76eaf3074fbe8babb5534f455efe15f8ed51047e7b6764f9668e8f9e02b4f3571fafb2feace81703bf6d82ad8d7f0ebe25ff99f9d7c4332230644b3c2b7fc8d91d4a8525fe191f1fcd3fa5584bfcc6e2fab1f26fc1bfec7383773730cfff0d9a7f46edf84f03835831edfcc1f1baf74f58fc3bcd328e953e3baf363ee2e117e7c6e9df4633ffb9f9b38ae7e46f891fd5eb0f36ff8afe73f2b7ac352cf91fd2c0023f6dc1bbf37767e9bf2dff5f8c4a24edfc13c85fd5f51f2b7fdaf31fc6070700e2dbc60a33ff1a0d30f3df860fcddf62fea87f1699bf0b3f38fa3bc38f2cf81703f00bfd6fc347e6bf6efef69a7fedfcf0fd9bbef2cf860f0e00c56f34f1bcfcb7ce1f81f96bc787e56ff3b305fe153f7ed15191f95be2b7b35ad270f2b764ddb1f2e7cffc21348cb57eea008fee5f0ecaff96fc3b25f8b0261cf8a006c0fc6b338efe965973cf86f7e6ef2c6bef66d6fc0bc2df8ac65754df92ff117dd8d3fd8baef1d14df48adf6eeee2f69a7f5de223f79f58fa49ffd8f3372c7fee46e397f91b577fcff017ec785ffe4e3bc87f21fd1b46fe39f0b10d88e143ae9d63fe08c2bbf217e50fc9bf96cf58f9333b635a3d31423fa7f42717daf0cf02f11b597bfdeecbbf0a1ec9dfda32a6868f9a834f3c96f0099ff0a7177f3c70ff133ee1133e1e9ff23fe1137eb878347f7d0e9cf6f8133ee1878cd7cedf94ff099ff0f178347fd5f3dfe300489ff009df297ef0f9e769c08f77371080777601187ec2277ca778f5fc05f5d3e74100ded94008de1502e47cc227bcc7069fbf78fe43faeb6b2004efeac47864c227fc39c87fbc7e87f5db154310ded100e2fb79c06baf3fd5f307c57b22f0e371fd44f1b8fec6e79faf8140bcb50f6271a1f8733ffe51bc7afd8ae2f1fc75b9108407ea5f5f0861783c7f6d0d84e26d0d443b1ecaaf8d1f7cfea078547f61fd565dbffa1a08c40f367f7d0d7861d69eeb099ff20fc4c3fbcf285e75fdea6b20101f5d3ffb3c08c6c7e6af278478cfc3f9513cac1f281e1dbff0f8d7c60f3fff06abbf4b43f1ad0ec43333f0eae31f1dbff0f8d7c6a3f9a75fffa2784b03e1f801e72f8cb7747e303ee50f8887f54f1b8feb278a3fcff96b0f60fed5dd7d4e432b7ead6793fb77e2f185138f1f7e17c27ffcc8fff761ac767c927df4701c8f2fec5ff72178f608c43f7e08c13f79fc1284ff37d2fdc94e81dd03f2375bffe4f103207f8f4f9e82f9fbfc3f0f80fc3d3e598f07cbd84718fce9c713553c3a7f648f307832d410fda7f183cc1f94ff083be53f82cfd0fc6715615d18187f81ff0c84c7ae1fcd1f183e196ab75e43d0cfd7eebee03fcb6a70fe3e5fc3f068fe3fc5f019e8bf40feebe2b397417c32d02ed8fe07b12083c72f863f46f110bab0e7285eb7fff0fc07f99369dbf66711b4faf845f1181c36f5f853fe9e7783fe9b9dc1eb1f064f962c1960caf3c731cc0fe293254b166d68fe6ae393254b166fdaf9ab8e479f5f507ffe2159b2e19a7afe6be3c1f9431b9f2c1962f0f8d5cedf84d7c5a7f9eb7cdbc0f5131dff2709af8a4f960c3174fec0c73ff8fc278c87e0eaf864c9104bf90fc1d5f1c9922186d7ffdaf9ab9bff9aebb70b4bbb78e9caebd7ab8797ae5e3bac1eef1e5cbfb13cbeb4bbf7fae18dead77bd70e6f568ef7f6afdda81cefeeed5fbf71ab02dfbf7cfd66e5786ffff2e1e2f8e2c5fd2b07d76ebef1e6fce812f97678ebdb6f19aeddabd76fdc7ce3addbe670efa000bf79fb4e79f6dee52b570f0bf0ed3b6f97715cbe5ab6551cbe4d4ded5e3928da2a0fbfb3f9c75f5e285f7ff8c5b7367ff393af6dbeffc32f6d3eb8f7d5cd77bfff85cdf77ef0c5f2b3dffdec1be5f70f7fbd5b9efbd777f737ff7cffd2e69f7e75b13c36e77cf8e3af2cdee9f5c18fbe5cbe1b2c61e8e72a1f7d46c7bffde9d7cbf3e945bc744cdf932ff4fafdcfbfb938d7bce87b6a97380943af77bef75af939f94f6dd177f432fed2cfd577f283da270c9d6fb0f419f94efd41be5431745cf8b365e2228c899770e483698bdec95783233fe855e04abcf98c7888975ef4b3e1357dfa9777f6ca77ea076a6fde46796cda212e3a3631d3e7744ce7d1cf7f7bef72f9fac70757cb776a93aea56983de4dcce61ad2e7868bcefffbfb57ca9f291e3aa677131b9d6fae17e1e8736ad38c13c29a971947c607331e8cdf669cd08bce31e7198c39e79f1f1e2cf0c617e32bf94ded55fbdff48de977c2527f10c68c6bc29a18cd98a7cfcd982ce2dca297e91b83317d427d6bda32d7cbf46fd1c656c1bf55f4f196191b2646931f86db5c4bea4f3a97ae0b8d71e22ec618f9b0e0a88eadf978d82adad8227fcd18a7b6e6e3abc417afff0309a69f37";
            string test3 = "7801EDDC310D00000803B02508C0BF5B828A3DAD904E920900000000000000000000000000000000000000000000000000000000000000F016000000000000000000000000000000A86BFF03000000000000000000000000000000000000000000000000000000000000000040CF01072DC034";

            //$ordered = zlib_encode(
            //int chunkX) .
            //int chunkZ) .
            //$orderedIds .
            //$orderedData .
            //$orderedSkyLight .
            //$orderedLight .
            //$this->biomeIds .
            //$biomeColors .
            //$this->tiles


            byte[] val = SoapHexBinary.Parse(test).Value;
            Assert.IsNotNull(val);


            MemoryStream stream = new MemoryStream(val);

            if (stream.ReadByte() != 0x78)
            {
                throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
            }
            stream.ReadByte();
            using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
            {
                NbtBinaryReader defStream = new NbtBinaryReader(defStream2, true);
                ChunkColumn     chunk     = new ChunkColumn();

                chunk.x = IPAddress.NetworkToHostOrder(defStream.ReadInt32());
                chunk.z = IPAddress.NetworkToHostOrder(defStream.ReadInt32());

                int chunkSize = 16 * 16 * 128;
                Assert.AreEqual(chunkSize, defStream.Read(chunk.blocks, 0, chunkSize));
                Assert.AreEqual(chunkSize / 2, defStream.Read(chunk.metadata.Data, 0, chunkSize / 2));
                Assert.AreEqual(chunkSize / 2, defStream.Read(chunk.skylight.Data, 0, chunkSize / 2));
                Assert.AreEqual(chunkSize / 2, defStream.Read(chunk.blocklight.Data, 0, chunkSize / 2));

                Assert.AreEqual(256, defStream.Read(chunk.biomeId, 0, 256));

                byte[] ints = new byte[256 * 4];
                Assert.AreEqual(ints.Length, defStream.Read(ints, 0, ints.Length));
                int j = 0;
                for (int i = 0; i < ints.Length; i = i + 4)
                {
                    chunk.biomeColor[j++] = BitConverter.ToInt32(new[] { ints[i], ints[i + 1], ints[i + 2], ints[i + 3] }, 0);
                }

                MemoryStream uncompressed = new MemoryStream();
                int          b            = -1;
                do
                {
                    b = defStream2.ReadByte();
                    if (b != -1)
                    {
                        uncompressed.WriteByte((byte)b);
                    }
                } while (b != -1);

                Assert.AreEqual(0, uncompressed.Length);
                //Assert.AreEqual(83208, uncompressed.Length);
                Assert.AreEqual(8, chunk.x);
                Assert.AreEqual(9, chunk.z);
                byte[] data = chunk.GetBytes(false);
                Assert.AreEqual(83208, data.Length);                 // Expected uncompressed length
            }
        }
示例#28
0
        public void TestRealDecrytp()
        {
            // YFtS5MGIU/UQ2w2n3RdqMoBcHOzqEQqISOyKD+W9Prk=

            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.BlockSize    = 128;
                rijAlg.Padding      = PaddingMode.None;
                rijAlg.Mode         = CipherMode.CFB;
                rijAlg.FeedbackSize = 8;

                rijAlg.Key = Base64Url.Decode("Tv9JFj4vhftDXgcjpNWNocWZrVKaVpF+icEh51M8MvI=");
                rijAlg.IV  = rijAlg.Key.Take(16).ToArray();

                Assert.AreEqual(rijAlg.Key.Take(16).ToArray(), rijAlg.IV);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream())
                {
                    byte[] buffer1 = SoapHexBinary.Parse("172e0592aba239d86b7ca2384cfad4e4fa5b883ff6db73931ecd").Value;
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        msDecrypt.Write(buffer1, 0, buffer1.Length);
                        msDecrypt.Position = 0;
                        byte[] checksum;
                        byte[] clearBytes;
                        using (var clearBuffer = new MemoryStream())
                        {
                            var buffer = new byte[1024];
                            var read   = csDecrypt.Read(buffer, 0, buffer.Length);
                            while (read > 0)
                            {
                                clearBuffer.Write(buffer, 0, read);
                                read = csDecrypt.Read(buffer, 0, buffer.Length);
                            }
                            csDecrypt.Flush();

                            var fullResult = clearBuffer.ToArray();
                            clearBytes = (byte[])fullResult.Take(fullResult.Length - 8).ToArray();
                            checksum   = fullResult.Skip(fullResult.Length - 8).ToArray();
                        }

                        Assert.AreEqual(6, clearBytes[0]);

                        Package message = PackageFactory.CreatePackage(clearBytes[0], clearBytes, "mcpe");
                        Assert.NotNull(message);
                        Assert.AreEqual(typeof(McpeWrapper), message.GetType());

                        List <Package> messages           = HandleBatch((McpeWrapper)message);
                        McpeClientToServerHandshake magic = (McpeClientToServerHandshake)messages.FirstOrDefault();
                        Assert.AreEqual(typeof(McpeClientToServerHandshake), magic?.GetType());

                        //Hashing - Checksum - Validation
                        MemoryStream hashStream = new MemoryStream();
                        Assert.True(BitConverter.IsLittleEndian);
                        hashStream.Write(BitConverter.GetBytes(0L), 0, 8);
                        hashStream.Write(clearBytes, 0, clearBytes.Length);
                        hashStream.Write(rijAlg.Key, 0, rijAlg.Key.Length);
                        SHA256Managed crypt              = new SHA256Managed();
                        var           hashBuffer         = hashStream.ToArray();
                        byte[]        validationCheckSum = crypt.ComputeHash(hashBuffer, 0, hashBuffer.Length).Take(8).ToArray();
                        Assert.AreEqual(checksum, validationCheckSum);
                    }
                }
            }
        }
示例#29
0
        public static byte[] GetStringToBytes(string value)
        {
            SoapHexBinary shb = SoapHexBinary.Parse(value);

            return(shb.Value);
        }
示例#30
0
        /// <summary>
        /// Gets an object instance out of an XML string and an XML schema type.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="schemaType"></param>
        /// <returns></returns>
        public static object ToClr(string value, string schemaType)
        {
            switch (schemaType.ToLower())
            {
            case "anyuri":
                return(new Uri(value));

            case "base64binary":
                return(Convert.FromBase64String(value));

            case "boolean":
                return(XmlConvert.ToBoolean(value));

            case "byte":
                return(XmlConvert.ToSByte(value));

            case "date":
            case "datetime":
            case "gday":
            case "gmonth":
            case "gmonthday":
            case "gyear":
            case "gyearmonth":
            case "time":
                return(XmlConvert.ToDateTime(value, XmlDateTimeSerializationMode.Utc));

            case "decimal":
            case "integer":
            case "negativeinteger":
            case "nonnegativeinteger":
            case "nonpositiveinteger":
            case "positiveinteger":
                return(XmlConvert.ToDecimal(value));

            case "double":
                return(XmlConvert.ToDouble(value));

            case "duration":
                return(XmlConvert.ToTimeSpan(value));

            case "entities":
            case "idrefs":
            case "nmtokens":
                return(value.Split(' '));

            case "entity":
            case "id":
            case "idref":
            case "language":
            case "name":
            case "ncname":
            case "nmtoken":
            case "normalizedstring":
            case "notation":
            case "string":
            case "token":
                return(value);

            case "float":
                return(XmlConvert.ToSingle(value));

            case "hexbinary":
                return(SoapHexBinary.Parse(value).Value);

            case "int":
                return(XmlConvert.ToInt32(value));

            case "long":
                return(XmlConvert.ToInt64(value));

            case "qname":
                string[] qNameTuple = value.Split(':');
                return(new XmlQualifiedName(qNameTuple[0], qNameTuple[1]));

            case "short":
                return(XmlConvert.ToInt16(value));

            case "unsignedbyte":
                return(XmlConvert.ToByte(value));

            case "unsignedint":
                return(XmlConvert.ToUInt32(value));

            case "unsignedlong":
                return(XmlConvert.ToUInt64(value));

            case "unsignedshort":
                return(XmlConvert.ToUInt16(value));

            default:
                throw new ArgumentException(schemaType + " is not a valid schema type");
            }
        }