Example #1
0
        public void WriteBytes(ulong offset, byte[] data)
        {
            ulong currentSize      = this.Length;
            ulong nextBytePosition = offset + (uint)data.Length;

            if (nextBytePosition > currentSize)
            {
                // Data needs to be extended
                ulong additionalLength = nextBytePosition - currentSize;
                Extend(additionalLength);
            }

            long firstSectorIndex    = (long)(offset / (uint)m_volume.BytesPerSector);
            int  offsetInFirstSector = (int)(offset % (uint)m_volume.BytesPerSector);
            // Note that the calculation of lastSectorIndex is only correct when nextBytePosition % BytesPerSector > 0
            long lastSectorIndex    = (long)(nextBytePosition / (uint)m_volume.BytesPerSector);
            int  offsetInLastSector = (int)(nextBytePosition % (uint)m_volume.BytesPerSector);

            if (offsetInFirstSector > 0 && offsetInLastSector > 0 && firstSectorIndex == lastSectorIndex)
            {
                byte[] sectorBytes = ReadSectors(firstSectorIndex, 1);
                ByteWriter.WriteBytes(sectorBytes, offsetInFirstSector, data);
                data = sectorBytes;
            }
            else
            {
                if (offsetInFirstSector > 0)
                {
                    byte[] firstSectorBytes = ReadSectors(firstSectorIndex, 1);
                    byte[] bytesToKeep      = ByteReader.ReadBytes(firstSectorBytes, 0, offsetInFirstSector);
                    data = ByteUtils.Concatenate(bytesToKeep, data);
                }

                if (offsetInLastSector > 0)
                {
                    byte[] lastSectorBytes = ReadSectors(lastSectorIndex, 1);
                    byte[] bytesToKeep     = ByteReader.ReadBytes(lastSectorBytes, offsetInLastSector, lastSectorBytes.Length - offsetInLastSector);
                    data = ByteUtils.Concatenate(data, bytesToKeep);
                }
            }

            WriteSectors(firstSectorIndex, data);
        }
Example #2
0
        public static WalletFile CreateWalletFile(
            ECKeyPair ecKeyPair, byte[] cipherText, byte[] iv, byte[] salt, byte[] mac,
            int n, int p)
        {
            var walletFile = new WalletFile
            {
                Address = ecKeyPair.GetHexAddress()
            };

            var crypto = new Crypto
            {
                Cipher     = CIPHER,
                Ciphertext = ByteUtils.ToHexString(cipherText, null)
            };

            walletFile.Crypto = crypto;

            var cipherParams = new CipherParams
            {
                IV = ByteUtils.ToHexString(iv, null)
            };

            crypto.Cipherparams = cipherParams;

            crypto.Kdf = SCRYPT;
            var kdfParams = new ScryptKdfParams
            {
                Dklen = DKLEN,
                N     = n,
                P     = p,
                R     = R,
                Salt  = ByteUtils.ToHexString(salt, null)
            };

            crypto.Kdfparams = kdfParams;

            crypto.Mac         = ByteUtils.ToHexString(mac, null);
            walletFile.Crypto  = crypto;
            walletFile.Id      = Guid.NewGuid().ToString();
            walletFile.Version = CURRENT_VERSION;

            return(walletFile);
        }
Example #3
0
        public static void VerifyDuplicateKey_RefCounts()
        {
            byte[] data = ByteUtils.RepeatByte(0x74, 11);
            byte[] signature;
            ECDsa  second;

            using (ECDsaOpenSsl first = new ECDsaOpenSsl())
                using (SafeEvpPKeyHandle firstHandle = first.DuplicateKeyHandle())
                {
                    signature = first.SignData(data, HashAlgorithmName.SHA384);
                    second    = new ECDsaOpenSsl(firstHandle);
                }

            // Now show that second still works, despite first and firstHandle being Disposed.
            using (second)
            {
                Assert.True(second.VerifyData(data, signature, HashAlgorithmName.SHA384));
            }
        }
        protected internal virtual void InitCryptoIfSpecified(PdfVersion version)
        {
            EncryptionProperties encryptProps = properties.encryptionProperties;

            if (properties.IsStandardEncryptionUsed())
            {
                crypto = new PdfEncryption(encryptProps.userPassword, encryptProps.ownerPassword, encryptProps.standardEncryptPermissions
                                           , encryptProps.encryptionAlgorithm, ByteUtils.GetIsoBytes(this.document.GetOriginalDocumentId().GetValue
                                                                                                         ()), version);
            }
            else
            {
                if (properties.IsPublicKeyEncryptionUsed())
                {
                    crypto = new PdfEncryption(encryptProps.publicCertificates, encryptProps.publicKeyEncryptPermissions, encryptProps
                                               .encryptionAlgorithm, version);
                }
            }
        }
        public static int Decode(byte[] data, int offset, int size, out byte[] result)
        {
            if (size < LENGTH_SIZE)              //包头还没有收完(ushort=4bytes)
            {
                result = null;
                return(-1);
            }
            int length = 0;

            ByteUtils.Decode32i(data, offset, ref length);
            if (length > size)              //还没有足够数组
            {
                result = null;
                return(-1);
            }
            result = new byte[length - LENGTH_SIZE];
            System.Buffer.BlockCopy(data, offset + LENGTH_SIZE, result, 0, length - LENGTH_SIZE);
            return(length);
        }
Example #6
0
        public void TestDecryption_Rfc3610_Packet_Vector1()
        {
            byte[] key = { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF };

            byte[] nonce = { 0x00, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 };

            byte[] associatedData = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

            byte[] encryptedData = { 0x58, 0x8C, 0x97, 0x9A, 0x61, 0xC6, 0x63, 0xD2, 0xF0, 0x66, 0xD0, 0xC2, 0xC0, 0xF9, 0x89, 0x80,
                                     0x6D, 0x5F, 0x6B, 0x61, 0xDA, 0xC3, 0x84 };

            byte[] signature = { 0x17, 0xE8, 0xD1, 0x2C, 0xFD, 0xF9, 0x26, 0xE0 };

            byte[] expectedData = { 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E };

            byte[] data = AesCcm.DecryptAndAuthenticate(key, nonce, encryptedData, associatedData, signature);

            Assert.True(ByteUtils.AreByteArraysEqual(expectedData, data));
        }
Example #7
0
        private GatRowSet BuildThriftRowSet(IGatRowSet rowSet)
        {
            GatRowSet ret = new GatRowSet();

            ret.Columns = new List <GatColumn>();
            foreach (IGatColumn column in rowSet.Columns)
            {
                GatColumn col = new GatColumn();
                col.Name          = column.Name;
                col.Ordinal       = column.Ordinal;
                col.Type          = new GatColumnType();
                col.Type.Type     = (Gat.Event.Thrift.GatDataType)(int) column.Type.Type;
                col.Type.TypeName = column.Type.TypeName;
                if (column.Type.Precision.HasValue)
                {
                    col.Type.Precision = column.Type.Precision.Value;
                }
                if (column.Type.Scale.HasValue)
                {
                    col.Type.Scale = column.Type.Scale.Value;
                }
                ret.Columns.Add(col);
            }
            ret.Rows = new List <GatRow>();
            foreach (IGatRow row in rowSet.Rows)
            {
                GatRow r = new GatRow();
                r.Values = new List <GatValue>();
                foreach (IGatValue value in row.Values)
                {
                    GatValue val = new GatValue();
                    val.Ordinal = value.Ordinal;
                    object valObj = value.GetValue <object>();
                    if (valObj != null)
                    {
                        val.Value = ByteUtils.ToByteArray(valObj);
                    }
                    r.Values.Add(val);
                }
            }
            return(ret);
        }
Example #8
0
        public void TestLMMIC()
        {
            string password = "******";

            byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00, 0x97, 0x82, 0x08, 0xe2,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x06, 0x01, 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f };
            byte[] type2 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00,
                                        0x38, 0x00, 0x00, 0x00, 0x95, 0x00, 0x82, 0xa2, 0x28, 0x96, 0xe3, 0x6a, 0xd1, 0xb7, 0x74, 0xb8,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x3e, 0x00, 0x00, 0x00,
                                        0x05, 0x02, 0xce, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x02, 0x00,
                                        0x06, 0x00, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x01, 0x00, 0x06, 0x00, 0x54, 0x00, 0x41, 0x00,
                                        0x4c, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] type3 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00,
                                        0x7c, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x94, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00,
                                        0x58, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x66, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00,
                                        0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xac, 0x00, 0x00, 0x00, 0x95, 0x00, 0x80, 0xa2,
                                        0x06, 0x01, 0xb1, 0x1d, 0x00, 0x00, 0x00, 0x0f, 0x4e, 0x65, 0x54, 0xe6, 0xb3, 0xdc, 0xdc, 0x16,
                                        0xef, 0xc4, 0xd0, 0x03, 0x3b, 0x81, 0x61, 0x6f, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00,
                                        0x56, 0x00, 0x4d, 0x00, 0x37, 0x00, 0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x54, 0x00,
                                        0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x37, 0x00, 0xc1, 0xd1, 0x06, 0x56,
                                        0xa3, 0xa9, 0x64, 0x14, 0x0e, 0x7f, 0x43, 0x19, 0x3f, 0x29, 0xf3, 0x72, 0xa3, 0xc1, 0xbe, 0x02,
                                        0xd0, 0x6f, 0xff, 0x20, 0xc1, 0xd1, 0x06, 0x56, 0xa3, 0xa9, 0x64, 0x14, 0x0e, 0x7f, 0x43, 0x19,
                                        0x3f, 0x29, 0xf3, 0x72, 0xa3, 0xc1, 0xbe, 0x02, 0xd0, 0x6f, 0xff, 0x20 };

            byte[] serverChallenge = new ChallengeMessage(type2).ServerChallenge;
            AuthenticateMessage authenticateMessage = new AuthenticateMessage(type3);

            byte[] sessionBaseKey     = new MD4().GetByteHashFromBytes(NTLMCryptography.NTOWFv1(password));
            byte[] lmowf              = NTLMCryptography.LMOWFv1(password);
            byte[] exportedSessionKey = GetExportedSessionKey(sessionBaseKey, authenticateMessage, serverChallenge, lmowf);

            // https://msdn.microsoft.com/en-us/library/cc236695.aspx
            const int micFieldOffset = 72;

            ByteWriter.WriteBytes(type3, micFieldOffset, new byte[16]);
            byte[] temp     = ByteUtils.Concatenate(ByteUtils.Concatenate(type1, type2), type3);
            byte[] mic      = new HMACMD5(exportedSessionKey).ComputeHash(temp);
            byte[] expected = new byte[] { 0x4e, 0x65, 0x54, 0xe6, 0xb3, 0xdc, 0xdc, 0x16, 0xef, 0xc4, 0xd0, 0x03, 0x3b, 0x81, 0x61, 0x6f };

            Assert.IsTrue(ByteUtils.AreByteArraysEqual(mic, expected));
        }
        public void MaskShouldBePreviousSequences()
        {
            uint[] expectedMask1 = new uint[5] {
                0b0,    // no received
                0b1,    // i=0 received
                0b1,    // still just i=0
                0b1,    // still just i=0
                0b1001, // received i=3
            };
            uint[] expectedMask2 = new uint[5] {
                0b0,    // i=0 not received
                0b1,    // i=1 received
                0b11,   // i=2 received
                0b11,   // still just i=2
                0b1101, // received i=4
            };
            uint[] mask = new uint[5];

            for (int i = 0; i < messageCount; i++)
            {
                int offset = 5;
                mask[i] = ByteUtils.ReadUInt(instance1.packet(i), ref offset);
            }
            // do 2nd loop so we can log all values to debug
            for (int i = 0; i < messageCount; i++)
            {
                Assert.That(mask[i], Is.EqualTo(expectedMask1[i]), $"Received should contain previous receives\n  instance 1, index{i}\n{string.Join(",", mask.Select(x => x.ToString()))}");
            }


            // start at 1
            for (int i = 0; i < messageCount; i++)
            {
                int offset = 5;
                mask[i] = ByteUtils.ReadUInt(instance2.packet(i), ref offset);
            }
            // do 2nd loop so we can log all values to debug
            for (int i = 0; i < messageCount; i++)
            {
                Assert.That(mask[i], Is.EqualTo(expectedMask2[i]), $"Received should contain previous receives\n  instance 2, index{i}\n{string.Join(",", mask.Select(x => x.ToString()))}");
            }
        }
Example #10
0
        /// <summary>
        /// This test checks that attributes are deep cloned when assembled from FileRecordSegment list and sliced into FileRecordSegment list.
        /// </summary>
        public static void AttributeCloneTest()
        {
            byte minorNTFSVersion                     = 1;
            int  bytesPerFileRecordSegment            = 1024;
            FileRecordSegment       baseSegment       = new FileRecordSegment(30, 1);
            FileRecordSegment       segment2          = new FileRecordSegment(31, 1, baseSegment.SegmentReference);
            FileNameRecord          fileNameRecord    = new FileNameRecord(NTFSVolume.RootDirSegmentReference, "john.txt", false, DateTime.Now);
            FileNameAttributeRecord fileNameAttribute = new FileNameAttributeRecord(String.Empty);

            fileNameAttribute.Record = fileNameRecord;
            NonResidentAttributeRecord dataRecord = new NonResidentAttributeRecord(AttributeType.Data, String.Empty);

            baseSegment.ImmediateAttributes.Add(fileNameAttribute);
            baseSegment.ImmediateAttributes.Add(dataRecord);
            dataRecord.DataRunSequence.Add(new DataRun(5, 0));
            byte[] segmentBytesBefore = baseSegment.GetBytes(bytesPerFileRecordSegment, minorNTFSVersion, false);

            List <FileRecordSegment> segments = new List <FileRecordSegment>();

            segments.Add(baseSegment);
            segments.Add(segment2);
            FileRecord fileRecord = new FileRecord(segments);

            ((NonResidentAttributeRecord)fileRecord.DataRecord).DataRunSequence[0].RunLength = 8;
            fileRecord.FileNameRecord.ParentDirectory = new MftSegmentReference(8, 8);
            fileRecord.FileNameRecord.FileName        = "d";
            byte[] segmentBytesAfter = baseSegment.GetBytes(bytesPerFileRecordSegment, minorNTFSVersion, false);
            if (!ByteUtils.AreByteArraysEqual(segmentBytesBefore, segmentBytesAfter))
            {
                throw new Exception("Test failed");
            }

            fileRecord.UpdateSegments(1024, 1);
            byte[] segmentBytesBefore2 = fileRecord.Segments[0].GetBytes(bytesPerFileRecordSegment, minorNTFSVersion, false);
            ((NonResidentAttributeRecord)fileRecord.DataRecord).DataRunSequence[0].RunLength = 10;
            fileRecord.FileNameRecord.FileName = "x";
            byte[] segmentBytesAfter2 = fileRecord.Segments[0].GetBytes(bytesPerFileRecordSegment, minorNTFSVersion, false);
            if (!ByteUtils.AreByteArraysEqual(segmentBytesBefore2, segmentBytesAfter2))
            {
                throw new Exception("Test failed");
            }
        }
Example #11
0
        public static bool ValidateSpecialHashes(MachObjectFile file, byte[] infoFileBytes, byte[] codeResourcesBytes)
        {
            byte[] codeSignatureBytes = file.GetCodeSignatureBytes();
            if (CodeSignatureSuperBlob.IsCodeSignatureSuperBlob(codeSignatureBytes, 0))
            {
                CodeSignatureSuperBlob codeSignature = new CodeSignatureSuperBlob(codeSignatureBytes, 0);
                CodeDirectoryBlob      codeDirectory = codeSignature.GetEntry(CodeSignatureEntryType.CodeDirectory) as CodeDirectoryBlob;

                byte[] infoFileHash = HashAlgorithmHelper.ComputeHash(codeDirectory.HashType, infoFileBytes);
                if (!ByteUtils.AreByteArraysEqual(infoFileHash, codeDirectory.SpecialHashes[codeDirectory.SpecialHashes.Count - CodeDirectoryBlob.InfoFileHashOffset]))
                {
                    return(false);
                }

                byte[] codeResourcesHash = HashAlgorithmHelper.ComputeHash(codeDirectory.HashType, codeResourcesBytes);
                if (!ByteUtils.AreByteArraysEqual(codeResourcesHash, codeDirectory.SpecialHashes[codeDirectory.SpecialHashes.Count - CodeDirectoryBlob.CodeResourcesFileHashOffset]))
                {
                    return(false);
                }

                CodeRequirementsBlob codeRequirements = codeSignature.GetEntry(CodeSignatureEntryType.Requirements) as CodeRequirementsBlob;
                byte[] codeRequirementsBytes          = codeRequirements.GetBytes();
                byte[] codeRequirementsHash           = HashAlgorithmHelper.ComputeHash(codeDirectory.HashType, codeRequirementsBytes);
                if (!ByteUtils.AreByteArraysEqual(codeRequirementsHash, codeDirectory.SpecialHashes[codeDirectory.SpecialHashes.Count - CodeDirectoryBlob.RequirementsHashOffset]))
                {
                    return(false);
                }

                if (codeDirectory.SpecialHashes.Count >= CodeDirectoryBlob.EntitlementsHashOffset)
                {
                    CodeSignatureGenericBlob entitlements = codeSignature.GetEntry(CodeSignatureEntryType.Entitlements) as CodeSignatureGenericBlob;
                    byte[] entitlementsBytes = entitlements.GetBytes();
                    byte[] entitlementsHash  = HashAlgorithmHelper.ComputeHash(codeDirectory.HashType, entitlementsBytes);
                    if (!ByteUtils.AreByteArraysEqual(entitlementsHash, codeDirectory.SpecialHashes[codeDirectory.SpecialHashes.Count - CodeDirectoryBlob.EntitlementsHashOffset]))
                    {
                        return(false);
                    }
                }
                return(true);
            }
            return(false);
        }
Example #12
0
        public void TestNTLMv1MIC()
        {
            string password = "******";

            byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01, 0x00, 0x00, 0x00, 0x97, 0x82, 0x08, 0xe2,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                                        0x0a, 0x00, 0x39, 0x38, 0x00, 0x00, 0x00, 0x0f };
            byte[] type2 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00,
                                        0x38, 0x00, 0x00, 0x00, 0x15, 0x02, 0x82, 0xa2, 0xe8, 0xbe, 0x2f, 0x5b, 0xc5, 0xe9, 0xf7, 0xa7,
                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x3e, 0x00, 0x00, 0x00,
                                        0x05, 0x02, 0xce, 0x0e, 0x00, 0x00, 0x00, 0x0f, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x02, 0x00,
                                        0x06, 0x00, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x01, 0x00, 0x06, 0x00, 0x54, 0x00, 0x41, 0x00,
                                        0x4c, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] type3 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x03, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00,
                                        0x7c, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x94, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00,
                                        0x58, 0x00, 0x00, 0x00, 0x08, 0x00, 0x08, 0x00, 0x66, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x0e, 0x00,
                                        0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xac, 0x00, 0x00, 0x00, 0x15, 0x02, 0x80, 0xa2,
                                        0x0a, 0x00, 0x39, 0x38, 0x00, 0x00, 0x00, 0x0f, 0xae, 0xa7, 0xba, 0x44, 0x4e, 0x93, 0xa7, 0xdb,
                                        0xb3, 0x0c, 0x85, 0x49, 0xc2, 0x2b, 0xba, 0x9a, 0x54, 0x00, 0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00,
                                        0x56, 0x00, 0x4d, 0x00, 0x36, 0x00, 0x55, 0x00, 0x73, 0x00, 0x65, 0x00, 0x72, 0x00, 0x54, 0x00,
                                        0x41, 0x00, 0x4c, 0x00, 0x2d, 0x00, 0x56, 0x00, 0x4d, 0x00, 0x36, 0x00, 0xa6, 0x71, 0xbd, 0x94,
                                        0x78, 0x4f, 0x05, 0xf1, 0x3f, 0x3a, 0x7b, 0x41, 0xcf, 0x53, 0x2e, 0x36, 0x73, 0xe2, 0x14, 0x53,
                                        0xbd, 0x42, 0x5e, 0x8f, 0xa6, 0x71, 0xbd, 0x94, 0x78, 0x4f, 0x05, 0xf1, 0x3f, 0x3a, 0x7b, 0x41,
                                        0xcf, 0x53, 0x2e, 0x36, 0x73, 0xe2, 0x14, 0x53, 0xbd, 0x42, 0x5e, 0x8f };

            byte[] serverChallenge = new ChallengeMessage(type2).ServerChallenge;
            AuthenticateMessage authenticateMessage = new AuthenticateMessage(type3);

            byte[] sessionBaseKey     = new MD4().GetByteHashFromBytes(NTLMCryptography.NTOWFv1(password));
            byte[] lmowf              = NTLMCryptography.LMOWFv1(password);
            byte[] exportedSessionKey = GetExportedSessionKey(sessionBaseKey, authenticateMessage, serverChallenge, lmowf);

            // https://msdn.microsoft.com/en-us/library/cc236695.aspx
            const int micFieldOffset = 72;

            ByteWriter.WriteBytes(type3, micFieldOffset, new byte[16]);
            byte[] temp     = ByteUtils.Concatenate(ByteUtils.Concatenate(type1, type2), type3);
            byte[] mic      = new HMACMD5(exportedSessionKey).ComputeHash(temp);
            byte[] expected = new byte[] { 0xae, 0xa7, 0xba, 0x44, 0x4e, 0x93, 0xa7, 0xdb, 0xb3, 0x0c, 0x85, 0x49, 0xc2, 0x2b, 0xba, 0x9a };

            Assert.IsTrue(ByteUtils.AreByteArraysEqual(mic, expected));
        }
Example #13
0
        public static bool TestSerpent2()
        {
            SerpentManaged serpent = new SerpentManaged();

            serpent.Padding = PaddingMode.None;
            serpent.Mode    = CipherMode.ECB;
            byte[] key        = new byte[] { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] plaintext  = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
            byte[] ciphertext = new byte[] { 0xa2, 0x23, 0xaa, 0x12, 0x88, 0x46, 0x3c, 0x0e, 0x2b, 0xe3, 0x8e, 0xbd, 0x82, 0x56, 0x16, 0xc0 };

            byte[]           initializationVector = new byte[16];
            ICryptoTransform encryptor            = serpent.CreateEncryptor(key, initializationVector);
            ICryptoTransform decryptor            = serpent.CreateDecryptor(key, initializationVector);

            byte[] result1 = new byte[16];
            byte[] result2 = new byte[16];
            encryptor.TransformBlock(plaintext, 0, 16, result1, 0);
            decryptor.TransformBlock(ciphertext, 0, 16, result2, 0);
            return(ByteUtils.AreByteArraysEqual(result1, ciphertext) && ByteUtils.AreByteArraysEqual(result2, plaintext));
        }
Example #14
0
        public static bool TestSerpent()
        {
            SerpentManaged serpent = new SerpentManaged();

            serpent.Padding = PaddingMode.None;
            serpent.Mode    = CipherMode.ECB;
            byte[] key        = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
            byte[] plaintext  = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
            byte[] ciphertext = new byte[] { 0xde, 0x26, 0x9f, 0xf8, 0x33, 0xe4, 0x32, 0xb8, 0x5b, 0x2e, 0x88, 0xd2, 0x70, 0x1c, 0xe7, 0x5c };

            byte[]           initializationVector = new byte[16];
            ICryptoTransform encryptor            = serpent.CreateEncryptor(key, initializationVector);
            ICryptoTransform decryptor            = serpent.CreateDecryptor(key, initializationVector);

            byte[] result1 = new byte[16];
            byte[] result2 = new byte[16];
            encryptor.TransformBlock(plaintext, 0, 16, result1, 0);
            decryptor.TransformBlock(ciphertext, 0, 16, result2, 0);
            return(ByteUtils.AreByteArraysEqual(result1, ciphertext) && ByteUtils.AreByteArraysEqual(result2, plaintext));
        }
Example #15
0
            private static void HandleAllMessageInPacket(List <byte[]> messages, AckSystem.ReliableReceived received)
            {
                var array        = received.Buffer.array;
                var packetLength = received.Length;
                var offset       = 0;

                while (offset < packetLength)
                {
                    var length  = ByteUtils.ReadUShort(array, ref offset);
                    var message = new ArraySegment <byte>(array, offset, length);

                    var outBuffer = new byte[length];
                    Buffer.BlockCopy(array, offset, outBuffer, 0, length);
                    offset += length;
                    messages.Add(outBuffer);
                }

                // release buffer after all its message have been handled
                received.Buffer.Release();
            }
Example #16
0
    /// <summary>
    /// 设置房间自定义属性
    /// </summary>
    /// <param name="msg"></param>
    public override IMessage OnSetRoomProperty(ByteString msg)
    {
        Request request = new Request();

        ByteUtils.ByteStringToObject(request, msg);

        Reply reply = new Reply()
        {
            UserID = request.UserID,
            GameID = request.GameID,
            RoomID = request.RoomID,
            Errno  = ErrorCode.Ok,
            ErrMsg = "OnSetRoomProperty success"
        };
        string roomProperty = request.CpProto.ToStringUtf8();

        Logger.Info("OnSetRoomProperty start, userId={0}, gameId={1}, roomId={2}, roomProperty={3}", request.UserID, request.GameID, request.RoomID, roomProperty);

        return(reply);
    }
Example #17
0
        public String ReadString(int size, int offset = -1, bool countHeader = false)
        {
            if (countHeader)
            {
                inner.Seek(offset, SeekOrigin.Begin);
            }
            else if (offset == -1 && inner.Position < Globals.HeaderLength)
            {
                inner.Seek(Globals.HeaderLength, SeekOrigin.Begin);
            }
            else if (offset >= 0)
            {
                inner.Seek(offset + Globals.HeaderLength, SeekOrigin.Begin);
            }

            byte[] buffer = new byte[size];
            inner.Read(buffer, 0, size);

            return(ByteUtils.toString(buffer));
        }
Example #18
0
        /// <summary>
        /// Transfer amount, raw transaction will be encoded by rlp encoder and convert
        /// to hex string with prefix "0x". Then the hex string will be packaged into
        /// <seealso cref="TransferRequest"/> bean object and serialized to JSON string.
        /// </summary>
        /// <param name="transaction">
        ///            <seealso cref="RawTransaction"/> raw transaction to to send </param>
        /// <returns> <seealso cref="TransferResult"/> </returns>
        /// <exception cref="ClientIOException">
        ///             network error, 5xx http status means request error, 4xx http
        ///             status means no enough gas or balance. </exception>

        public static TransferResult Transfer(RawTransaction transaction)
        {
            if (transaction?.Signature == null)
            {
                throw ClientArgumentException.Exception("Raw transaction is invalid");
            }
            var rawBytes = transaction.Encode();

            if (rawBytes == null)
            {
                throw ClientArgumentException.Exception("Raw transaction is encode error");
            }
            string hexRaw  = ByteUtils.ToHexString(rawBytes, Prefix.ZeroLowerX);
            var    request = new TransferRequest
            {
                Raw = hexRaw
            };

            return(SendPostRequest <TransferResult>(Path.PostTransaction, null, null, request));
        }
        private static void GenericTest <TType>(TType[] value)
        {
            int size = ByteUtils.GetSizeOf(typeof(TType));

            byte[] buffer = new byte[value.Length * size];

            Action <byte[], int, object> writer = ByteUtils.GetBinaryWriter(typeof(TType));

            for (int i = 0; i < value.Length; i++)
            {
                writer(buffer, i * size, value[i]);
            }

            Func <byte[], int, object> reader = ByteUtils.GetBinaryReader(typeof(TType));

            for (int i = 0; i < value.Length; i++)
            {
                Assert.AreEqual(value[i], reader(buffer, i * size), typeof(TType).Name);
            }
        }
Example #20
0
        private static void SetMode(int mode)
        {
            var newMode = ByteUtils.IntByte(mode);
            var myDev   = DataUtil.GetDeviceData();
            var curMode = myDev.Mode;

            if (curMode == newMode)
            {
                LogUtil.Write("Old mode is same as new, nothing to do.");
                return;
            }

            myDev.Mode = mode;
            DataUtil.SetItem("MyDevice", myDev);
            var payload = new List <byte>();

            payload.Add((byte)mode);
            DreamSender.SendUdpWrite(0x01, 0x10, payload.ToArray(), 0x21, (byte)myDev.GroupNumber,
                                     new IPEndPoint(IPAddress.Parse(myDev.IpAddress), 8888));
        }
Example #21
0
        internal MosaicProperty(string propertyName, string propertyValue)
        {
            PropertyNameLength = Encoding.Default.GetBytes(propertyName).Length;

            PropertyValueLength = Encoding.Default.GetBytes(propertyValue).Length;

            PropertyLength += ByteLength.EightBytes + PropertyNameLength + PropertyValueLength;

            Serializer.WriteInt(PropertyLength);

            Serializer.WriteInt(PropertyNameLength);

            Serializer.WriteString(propertyName);

            Serializer.WriteInt(PropertyValueLength);

            Serializer.WriteString(propertyValue);

            PropertyBytes = ByteUtils.TruncateByteArray(Serializer.GetBytes(), PropertyLength + 4);
        }
Example #22
0
        public static void WriteToDisk(Disk disk, PrivateHeader privateHeader)
        {
            byte[] bytes = privateHeader.GetBytes();
            if (disk.BytesPerSector > Length)
            {
                bytes = ByteUtils.Concatenate(bytes, new byte[disk.BytesPerSector - PrivateHeader.Length]);
            }

            disk.WriteSectors((long)(privateHeader.PrivateRegionStartLBA + privateHeader.PrimaryPrivateHeaderLBA), bytes);
            disk.WriteSectors((long)(privateHeader.PrivateRegionStartLBA + privateHeader.SecondaryPrivateHeaderLBA), bytes);

            // update sector 6 if a Private Header is already present there
            byte[] sector    = disk.ReadSector(PrivateHeaderSectorIndex);
            string signature = ByteReader.ReadAnsiString(sector, 0x00, 8);

            if (signature == PrivateHeaderSignature)
            {
                disk.WriteSectors(PrivateHeaderSectorIndex, bytes);
            }
        }
Example #23
0
        public void WriteReadUIntTest()
        {
            var buffer = new byte[10];
            var offset = 3;
            // value large enough to use all 4 bytes
            uint value = 0x12_34_56_78;

            ByteUtils.WriteUInt(buffer, ref offset, value);
            Assert.That(offset, Is.EqualTo(7), "Should have moved offset by 4");
            Assert.That(buffer[3], Is.Not.Zero, "Should have written to buffer");
            Assert.That(buffer[4], Is.Not.Zero, "Should have written to buffer");
            Assert.That(buffer[5], Is.Not.Zero, "Should have written to buffer");
            Assert.That(buffer[6], Is.Not.Zero, "Should have written to buffer");

            offset = 3;
            var outValue = ByteUtils.ReadUInt(buffer, ref offset);

            Assert.That(offset, Is.EqualTo(7), "Should have moved offset by 4");
            Assert.That(outValue, Is.EqualTo(value), "Out value should be equal to in value");
        }
Example #24
0
        public static bool TestTwofish()
        {
            TwofishManaged twofish = new TwofishManaged();

            twofish.Padding = PaddingMode.None;
            twofish.Mode    = CipherMode.ECB;
            byte[] key        = new byte[] { 0xD4, 0x3B, 0xB7, 0x55, 0x6E, 0xA3, 0x2E, 0x46, 0xF2, 0xA2, 0x82, 0xB7, 0xD4, 0x5B, 0x4E, 0x0D, 0x57, 0xFF, 0x73, 0x9D, 0x4D, 0xC9, 0x2C, 0x1B, 0xD7, 0xFC, 0x01, 0x70, 0x0C, 0xC8, 0x21, 0x6F };
            byte[] plaintext  = new byte[] { 0x90, 0xAF, 0xE9, 0x1B, 0xB2, 0x88, 0x54, 0x4F, 0x2C, 0x32, 0xDC, 0x23, 0x9B, 0x26, 0x35, 0xE6 };
            byte[] ciphertext = new byte[] { 0x6C, 0xB4, 0x56, 0x1C, 0x40, 0xBF, 0x0A, 0x97, 0x05, 0x93, 0x1C, 0xB6, 0xD4, 0x08, 0xE7, 0xFA };

            byte[]           initializationVector = new byte[16];
            ICryptoTransform encryptor            = twofish.CreateEncryptor(key, initializationVector);
            ICryptoTransform decryptor            = twofish.CreateDecryptor(key, initializationVector);

            byte[] result1 = new byte[16];
            byte[] result2 = new byte[16];
            encryptor.TransformBlock(plaintext, 0, 16, result1, 0);
            decryptor.TransformBlock(ciphertext, 0, 16, result2, 0);
            return(ByteUtils.AreByteArraysEqual(result1, ciphertext) && ByteUtils.AreByteArraysEqual(result2, plaintext));
        }
Example #25
0
        /// <inheritdoc />
        public byte[] GetBytes()
        {
            var bytes = new List <byte>();

            var nameBytes = Encoding.ASCII.GetBytes(Name.Length > 12 ? Name.Substring(0, 12) : Name);

            bytes.AddRange(nameBytes);
            bytes.AddRange(ByteUtils.RepeatReserve(12 - nameBytes.Length, 0x20));

            bytes.Add(0x00);

            bytes.AddRange(Lfo.GetBytes());
            bytes.AddRange(Oscillator.GetBytes());
            bytes.AddRange(Filter.GetBytes());
            bytes.AddRange(Amplifier.GetBytes());
            bytes.AddRange(Common.GetBytes());
            bytes.AddRange(LfoModControl.GetBytes());

            return(bytes.ToArray());
        }
Example #26
0
 public override String ToString()
 {
     if (content != null)
     {
         return(iText.IO.Util.JavaUtil.GetStringForBytes(content, iText.IO.Util.EncodingUtil.ISO_8859_1));
     }
     else
     {
         if (isDouble)
         {
             return(iText.IO.Util.JavaUtil.GetStringForBytes(ByteUtils.GetIsoBytes(GetValue()), iText.IO.Util.EncodingUtil.ISO_8859_1
                                                             ));
         }
         else
         {
             return(iText.IO.Util.JavaUtil.GetStringForBytes(ByteUtils.GetIsoBytes(IntValue()), iText.IO.Util.EncodingUtil.ISO_8859_1
                                                             ));
         }
     }
 }
Example #27
0
        public bool ShouldBeInvalidIfFragmentIsOverMax(int differenceToMax)
        {
            int max = config.MaxReliableFragments;

            byte[] badPacket = new byte[AckSystem.MIN_RELIABLE_FRAGMENT_HEADER_SIZE];
            int    offset    = 0;

            // write as if it is normal packet
            ByteUtils.WriteByte(badPacket, ref offset, 0);
            ByteUtils.WriteUShort(badPacket, ref offset, 0);
            ByteUtils.WriteUShort(badPacket, ref offset, 0);
            ByteUtils.WriteULong(badPacket, ref offset, 0);
            ByteUtils.WriteUShort(badPacket, ref offset, 0);
            // write bad index (over max)
            int fragment = max + differenceToMax;

            ByteUtils.WriteByte(badPacket, ref offset, (byte)fragment);

            return(ackSystem.InvalidFragment(badPacket));
        }
Example #28
0
        public void TestEncryption_Rfc3610_Packet_Vector1()
        {
            byte[] key = new byte[] { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF };

            byte[] nonce = new byte[] { 0x00, 0x00, 0x00, 0x03, 0x02, 0x01, 0x00, 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 };

            byte[] data           = new byte[] { 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E };
            byte[] associatedData = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

            byte[] expectedEncrypted = new byte[] { 0x58, 0x8C, 0x97, 0x9A, 0x61, 0xC6, 0x63, 0xD2, 0xF0, 0x66, 0xD0, 0xC2, 0xC0, 0xF9, 0x89, 0x80,
                                                    0x6D, 0x5F, 0x6B, 0x61, 0xDA, 0xC3, 0x84 };

            byte[] expectedSignature = new byte[] { 0x17, 0xE8, 0xD1, 0x2C, 0xFD, 0xF9, 0x26, 0xE0 };

            byte[] calculatedSignature;
            byte[] encrypted = AesCcm.Encrypt(key, nonce, data, associatedData, 8, out calculatedSignature);

            Assert.IsTrue(ByteUtils.AreByteArraysEqual(expectedEncrypted, encrypted));
            Assert.IsTrue(ByteUtils.AreByteArraysEqual(expectedSignature, calculatedSignature));
        }
Example #29
0
        private void VerifyICryptoTransformStream(Stream input, string output)
        {
            byte[] expected = ByteUtils.HexToByteArray(output);
            byte[] actual;

            using (HashAlgorithm hash = Create())
                using (CryptoStream cryptoStream = new CryptoStream(input, hash, CryptoStreamMode.Read))
                {
                    byte[] buffer = new byte[1024]; // A different default than HashAlgorithm which uses 4K
                    int    bytesRead;
                    while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        // CryptoStream will build up the hash
                    }

                    actual = hash.Hash;
                }

            Assert.Equal(expected, actual);
        }
Example #30
0
        /// <summary>
        /// LM v1 / NTLM v1 Extended Security
        /// </summary>
        public User AuthenticateV1Extended(string accountNameToAuth, byte[] serverChallenge, byte[] lmResponse, byte[] ntlmResponse)
        {
            for (int index = 0; index < this.Count; index++)
            {
                string accountName = this[index].AccountName;
                string password    = this[index].Password;

                if (String.Equals(accountName, accountNameToAuth, StringComparison.InvariantCultureIgnoreCase))
                {
                    byte[] clientChallenge        = ByteReader.ReadBytes(lmResponse, 0, 8);
                    byte[] expectedNTLMv1Response = NTAuthentication.ComputeNTLMv1ExtendedSecurityResponse(serverChallenge, clientChallenge, password);

                    if (ByteUtils.AreByteArraysEqual(expectedNTLMv1Response, ntlmResponse))
                    {
                        return(this[index]);
                    }
                }
            }
            return(null);
        }