public void HmacRequires_AllArguments() { var hmacMock = new Mock <HMAC>(); var ex1 = Assert.Throws <ArgumentNullException>(() => ByteArrayExtensions.Hmac(null, hmacMock.Object)); var ex2 = Assert.Throws <ArgumentNullException>(() => new byte[0].Hmac(hmacMock.Object)); var ex3 = Assert.Throws <ArgumentNullException>(() => new byte[1].Hmac(null)); Assert.Equal("bytes", ex1.ParamName); Assert.Equal("bytes", ex2.ParamName); Assert.Equal("hmac", ex3.ParamName); }
/// <summary>Encode the value as an ILInt in the provided buffer, in the specified range.</summary> /// <param name="value">The value.</param> /// <param name="buffer">The buffer.</param> /// <param name="offset">The offset to start storing bytes in the buffer.</param> /// <param name="count">The maximum count of bytes that can be stored, it may not be enough in which case it throws.</param> /// <returns>The provided buffer.</returns> /// <exception cref="TooFewBytesException"></exception> public static byte[] ILIntEncode(this ulong value, byte[] buffer, int offset, int count) { ByteArrayExtensions.CheckBuffer(buffer, offset, count); ILIntEncode(value, b => { if (--count < 0) { throw new TooFewBytesException(); } buffer[offset++] = b; }); return(buffer); }
public void HashRequires_AllArguments() { var hashMock = new Mock <HashAlgorithm>(); var ex1 = Assert.Throws <ArgumentNullException>(() => ByteArrayExtensions.Hash(null, hashMock.Object)); var ex2 = Assert.Throws <ArgumentNullException>(() => new byte[0].Hash(hashMock.Object)); var ex3 = Assert.Throws <ArgumentNullException>(() => new byte[1].Hash(null)); Assert.Equal("bytes", ex1.ParamName); Assert.Equal("bytes", ex2.ParamName); Assert.Equal("algorithm", ex3.ParamName); }
internal override void WriteDataSimple(byte[] buffer, int offset) { byte[] bytes1 = Encoding.ASCII.GetBytes(this.Longitude); byte[] bytes2 = Encoding.ASCII.GetBytes(this.Latitude); byte[] bytes3 = Encoding.ASCII.GetBytes(this.Altitude); ByteArrayExtensions.Write(buffer, ref offset, (byte)bytes1.Length); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)bytes1); ByteArrayExtensions.Write(buffer, ref offset, (byte)bytes2.Length); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)bytes2); ByteArrayExtensions.Write(buffer, ref offset, (byte)bytes3.Length); ByteArrayExtensions.Write(buffer, ref offset, (IEnumerable <byte>)bytes3); }
public async Task AsyncGetByHashNotEmpty() { using var client = CreateClient(Configuration.LocalBaseUrl); var tx = await client.Transactions.GetByHashAsync( ByteArrayExtensions.ParseHexString(ExistingHash)); OutputHelper.WriteLine("Deserialized into"); Dump(tx); TxIsDelegateAndNotEmpty(tx); }
internal static void WriteHeader(byte[] buffer, int offset, IgmpMessageType igmpMessageType, TimeSpan maxResponseTime, IpV4Address groupAddress) { ByteArrayExtensions.Write(buffer, offset, (byte)igmpMessageType); double num = maxResponseTime.TotalSeconds * 10.0; if (num >= 256.0 || num < 0.0) { throw new ArgumentOutOfRangeException("maxResponseTime", (object)maxResponseTime, "must be in the range [" + (object)TimeSpan.Zero + ", " + (string)(object)TimeSpan.FromSeconds(25.5) + "]"); } ByteArrayExtensions.Write(buffer, offset + 1, (byte)num); ByteArrayExtensions.Write(buffer, offset + 4, groupAddress, Endianity.Big); IgmpDatagram.WriteChecksum(buffer, offset, 8); }
protected override sealed void Write(byte[] buffer, int offset) { this.WriteFirstLine(buffer, ref offset); if (this.Header != null) { this.Header.Write(buffer, ref offset); } if (this.Body == null) { return; } ByteArrayExtensions.Write(buffer, offset, (DataSegment)this.Body); }
internal static IpV4OptionTimestampAndAddress Read(IpV4OptionTimestampType timestampType, byte overflow, byte pointedIndex, byte[] buffer, ref int offset, int numValues) { if (numValues % 2 != 0) { return((IpV4OptionTimestampAndAddress)null); } IpV4OptionTimedAddress[] optionTimedAddressArray = new IpV4OptionTimedAddress[numValues / 2]; for (int index = 0; index != numValues / 2; ++index) { optionTimedAddressArray[index] = new IpV4OptionTimedAddress(ByteArrayExtensions.ReadIpV4Address(buffer, ref offset, Endianity.Big), ByteArrayExtensions.ReadIpV4TimeOfDay(buffer, ref offset, Endianity.Big)); } return(new IpV4OptionTimestampAndAddress(timestampType, overflow, pointedIndex, optionTimedAddressArray)); }
internal static void WriteReportVersion3(byte[] buffer, int offset, IEnumerable <IgmpGroupRecord> groupRecords) { ByteArrayExtensions.Write(buffer, offset, (byte)34); ushort num = (ushort)0; int offset1 = offset + 8; foreach (IgmpGroupRecord igmpGroupRecord in groupRecords) { IgmpGroupRecordDatagram.Write(buffer, ref offset1, igmpGroupRecord.RecordType, igmpGroupRecord.AuxiliaryData, igmpGroupRecord.MulticastAddress, igmpGroupRecord.SourceAddresses); ++num; } ByteArrayExtensions.Write(buffer, offset + 6, num, Endianity.Big); IgmpDatagram.WriteChecksum(buffer, offset, offset1 - offset); }
private IFirmataMessage HeaderGetMessage(MessageHeader messageHeader) { var value7Bit = messageHeader.MessageBuffer.Skip(3).Take(messageHeader.MessageBufferIndex - 3).Select(f => (byte)f).ToArray(); var value = ByteArrayExtensions.Decode7Bit(value7Bit); var currentState = new GenericResponse <byte[]> { MessageType = (byte)messageHeader.MessageBuffer[1], MessageSubType = (byte)messageHeader.MessageBuffer[2], Value = value }; return(new FirmataMessage <GenericResponse <byte[]> >(currentState)); }
//Arrange private HonoplayDbContext InitAndGetDbContext(out int adminUserId, out Guid tenantId, out Guid contentFileId) { var context = GetDbContext(); var salt = ByteArrayExtensions.GetRandomSalt(); var adminUser = new AdminUser { Email = "*****@*****.**", Password = "******".GetSHA512(salt), PasswordSalt = salt, LastPasswordChangeDateTime = DateTime.Today.AddDays(-5), }; context.AdminUsers.Add(adminUser); var tenant = new Tenant { Name = "TestTenant#01", HostName = "localhost" }; context.Tenants.Add(tenant); context.TenantAdminUsers.Add(new TenantAdminUser { TenantId = tenant.Id, AdminUserId = adminUser.Id, UpdatedBy = adminUser.Id }); var contentFile = new ContentFile { Id = Guid.NewGuid(), CreatedBy = adminUser.Id, Data = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 }, Name = "contentFile1", ContentType = "image/jpeg", TenantId = tenant.Id }; context.ContentFiles.Add(contentFile); context.SaveChanges(); adminUserId = adminUser.Id; contentFileId = contentFile.Id; tenantId = tenant.Id; return(context); }
/// <summary> /// decrypts a string /// </summary> /// <param name="inputText">string to decrypt</param> /// <returns>a decrypted string</returns> public string Decrypt(string inputText) { byte[] byteArr = ByteArrayExtensions.ToByteArrayBase64(inputText); string utf8String = ByteArrayExtensions.ToUTF8String(byteArr); return(utf8String); //F1 //return ComputeHash(inputText.ToByteArray()).ToHexString().ToUpper(); //F1 //convert back to a string //return Decrypt(inputText.ToByteArrayBase64()).ToUTF8String(); }
/// <summary> /// Creates an ID3v2 frame for the given key-value pair. /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> static byte[] CreateId3v2Frame(string key, string value) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (string.IsNullOrEmpty(value)) { throw new ArgumentNullException("value"); } if (key.Length != 4) { throw new ArgumentOutOfRangeException("key", "key " + key + " must be 4 characters long"); } const byte UnicodeEncoding = 01; // encode text in Unicode byte[] UnicodeOrder = new byte[] { 0xff, 0xfe }; // Unicode byte order mark byte[] language = new byte[] { 0, 0, 0 }; // language is empty (only used in COMM -> comment) byte[] shortDescription = new byte[] { 0, 0 }; // short description is empty (only used in COMM -> comment) byte[] body; if (key == "COMM") // comment { body = ByteArrayExtensions.Concat( new byte[] { UnicodeEncoding }, language, shortDescription, UnicodeOrder, Encoding.Unicode.GetBytes(value)); } else { body = ByteArrayExtensions.Concat( new byte[] { UnicodeEncoding }, UnicodeOrder, Encoding.Unicode.GetBytes(value)); } return(ByteArrayExtensions.Concat( // needs review - have converted to UTF8 as Win 8 has no Encoding.ASCII, // need to check what the rules are for ID3v2 tag identifiers Encoding.UTF8.GetBytes(key), FrameSizeToBytes(body.Length), new byte[] { 0, 0 }, // flags body)); }
private HonoplayDbContext InitAndGetDbContext(out int adminUserId, out int workingStatusId, out Guid tenantId) { var context = GetDbContext(); var salt = ByteArrayExtensions.GetRandomSalt(); var adminUser = new AdminUser { Name = "testAdmin", Email = "*****@*****.**", Password = "******".GetSHA512(salt), PasswordSalt = salt, LastPasswordChangeDateTime = DateTime.Today.AddDays(-5) }; context.AdminUsers.Add(adminUser); var tenant = new Tenant { Name = "TestTenant", HostName = "localhost", CreatedBy = adminUser.Id, }; context.Tenants.Add(tenant); context.TenantAdminUsers.Add(new TenantAdminUser { TenantId = tenant.Id, AdminUserId = adminUser.Id, CreatedBy = adminUser.Id }); var workingStatus = new WorkingStatus { Name = "testWorkingStatus", TenantId = tenant.Id, CreatedBy = adminUser.Id }; context.WorkingStatuses.Add(workingStatus); context.SaveChanges(); adminUserId = adminUser.Id; workingStatusId = workingStatus.Id; tenantId = tenant.Id; return(context); }
byte[] GetHashAttribute() { try { return(ByteArrayExtensions.FromHexString(GetRequiredAttribute("Hash"))); } catch (ArgumentException ex) { throw new CassetteDeserializationException("Bundle manifest element has invalid Hash attribute.", ex); } catch (FormatException ex) { throw new CassetteDeserializationException("Bundle manifest element has invalid Hash attribute.", ex); } }
internal static void Write(byte[] buffer, ref int offset, IgmpRecordType recordType, Datagram auxiliaryData, IpV4Address multicastAddress, ReadOnlyCollection <IpV4Address> sourceAddresses) { ByteArrayExtensions.Write(buffer, offset, (byte)recordType); ByteArrayExtensions.Write(buffer, offset + 1, (byte)(auxiliaryData.Length / 4)); int count = sourceAddresses.Count; ByteArrayExtensions.Write(buffer, offset + 2, (ushort)count, Endianity.Big); ByteArrayExtensions.Write(buffer, offset + 4, multicastAddress, Endianity.Big); for (int index = 0; index != count; ++index) { ByteArrayExtensions.Write(buffer, offset + 8 + 4 * index, sourceAddresses[index], Endianity.Big); } offset += 8 + count * 4; ByteArrayExtensions.Write(buffer, ref offset, (DataSegment)auxiliaryData); }
internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns, (ushort)this.TypeCovered, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 2, (byte)this.Algorithm); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 3, this.Labels); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 4, this.OriginalTtl, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 8, this.SignatureExpiration.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 12, this.SignatureInception.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, dnsOffset + offsetInDns + 16, this.KeyTag, Endianity.Big); int num1 = 18; int num2 = num1 + this.SignersName.Write(buffer, dnsOffset, compressionData, offsetInDns + num1); this.Signature.Write(buffer, dnsOffset + offsetInDns + num2); return(num2 + this.Signature.Length); }
private HonoplayDbContext InitAndGetDbContext(out Guid tenantId, out int adminUserId, out int traineeGroupId) { var context = GetDbContext(); var salt = ByteArrayExtensions.GetRandomSalt(); var adminUser = new AdminUser { Id = 1, Email = "*****@*****.**", Password = "******".GetSHA512(salt), PasswordSalt = salt, LastPasswordChangeDateTime = DateTime.Today.AddDays(-5), }; context.AdminUsers.Add(adminUser); var tenant = new Tenant { Name = "TestTenant#01", HostName = "localhost" }; context.Tenants.Add(tenant); context.TenantAdminUsers.Add(new TenantAdminUser { TenantId = tenant.Id, AdminUserId = adminUser.Id, UpdatedBy = adminUser.Id }); var traineeGroup = new TraineeGroup { TenantId = tenant.Id, Name = "Test1asd", UpdatedBy = adminUser.Id }; context.Add(traineeGroup); context.SaveChanges(); adminUserId = adminUser.Id; tenantId = tenant.Id; traineeGroupId = traineeGroup.Id; return(context); }
internal override void WriteDataSimple(byte[] buffer, int offset) { byte num1 = (byte)0; if (this.AuthenticationProhibited) { num1 |= (byte)sbyte.MinValue; } if (this.ConfidentialityProhibited) { num1 |= (byte)64; } if (this.Experimental) { num1 |= (byte)32; } if (this.UserAssociated) { num1 |= (byte)4; } if (this.FlagsExtension.HasValue) { num1 |= (byte)16; } byte num2 = (byte)((DnsKeyNameType)num1 | this.NameType & (DnsKeyNameType)3); ByteArrayExtensions.Write(buffer, offset, num2); byte num3 = (byte)0; if (this.IpSec) { num3 |= (byte)sbyte.MinValue; } if (this.Email) { num3 |= (byte)64; } byte num4 = (byte)((DnsKeySignatoryAttributes)num3 | this.Signatory & (DnsKeySignatoryAttributes.General | DnsKeySignatoryAttributes.Unique | DnsKeySignatoryAttributes.Strong | DnsKeySignatoryAttributes.Zone)); ByteArrayExtensions.Write(buffer, offset + 1, num4); ByteArrayExtensions.Write(buffer, offset + 2, (byte)this.Protocol); ByteArrayExtensions.Write(buffer, offset + 3, (byte)this.Algorithm); if (this.FlagsExtension.HasValue) { ByteArrayExtensions.Write(buffer, offset + 4, this.FlagsExtension.Value, Endianity.Big); } this.PublicKey.Write(buffer, offset + 4 + (this.FlagsExtension.HasValue ? 2 : 0)); }
public async Task <ResponseModel <RegisterAdminUserModel> > Handle(RegisterAdminUserCommand request, CancellationToken cancellationToken) { var salt = ByteArrayExtensions.GetRandomSalt(); var item = new AdminUser { Email = request.Email, Name = request.Name, Surname = request.Surname, TimeZone = request.TimeZone, CreatedDateTime = DateTimeOffset.Now, LastPasswordChangeDateTime = DateTimeOffset.Now, PasswordSalt = salt, Password = request.Password.GetSHA512(salt), }; using (IDbContextTransaction transaction = _context.Database.BeginTransaction()) { try { _context.Add(item); await _context.SaveChangesAsync(cancellationToken); transaction.Commit(); } catch (DbUpdateException ex) when((ex.InnerException is SqlException sqlException && (sqlException.Number == 2627 || sqlException.Number == 2601)) || (ex.InnerException is SqliteException sqliteException && sqliteException.SqliteErrorCode == 19)) { transaction.Rollback(); throw new ObjectAlreadyExistsException(nameof(AdminUser), nameof(AdminUser.Email)); } catch (Exception) { transaction.Rollback(); throw new TransactionException(); } } var model = new RegisterAdminUserModel(id: item.Id, email: item.Email, username: item.UserName, name: item.Name, surname: item.Surname, phoneNumber: item.PhoneNumber, timeZone: item.TimeZone, createDateTime: item.CreatedDateTime); return(new ResponseModel <RegisterAdminUserModel>(model)); }
//Arrange private HonoplayDbContext InitAndGetDbContext(out int adminUserId, out Guid tenantId, out int questionCategoryId) { var context = GetDbContext(); var salt = ByteArrayExtensions.GetRandomSalt(); var adminUser = new AdminUser { Email = "*****@*****.**", Password = "******".GetSHA512(salt), PasswordSalt = salt, LastPasswordChangeDateTime = DateTime.Today.AddDays(-5), }; context.AdminUsers.Add(adminUser); var tenant = new Tenant { Name = "TestTenant#01", HostName = "localhost" }; context.Tenants.Add(tenant); context.TenantAdminUsers.Add(new TenantAdminUser { TenantId = tenant.Id, AdminUserId = adminUser.Id, UpdatedBy = adminUser.Id }); var questionCategory = new QuestionCategory { Id = 1, CreatedBy = adminUser.Id, Name = "questionCategory1", TenantId = tenant.Id }; context.QuestionCategories.Add(questionCategory); context.SaveChanges(); adminUserId = adminUser.Id; questionCategoryId = questionCategory.Id; tenantId = tenant.Id; return(context); }
/// <summary> /// Creates the Id3v2 tag header and returns is as a byte array. /// </summary> /// <param name="frames">The Id3v2 frames that will be included in the file. This is used to calculate the ID3v2 tag size.</param> /// <returns></returns> static byte[] CreateId3v2TagHeader(IEnumerable <byte[]> frames) { int size = 0; foreach (byte[] frame in frames) { size += frame.Length; } byte[] tagHeader = ByteArrayExtensions.Concat( Encoding.UTF8.GetBytes("ID3"), new byte[] { 3, 0 }, // version new byte[] { 0 }, // flags GetId3TagHeaderSize(size)); return(tagHeader); }
private void HandleAuthSession(IPacket packet) { Stream dataStream = packet.GetStream(); BinaryReader r = packet.CreateReader(); uint version = r.ReadUInt32(); uint unk2 = r.ReadUInt32(); string accountName = r.ReadCString(); uint unk = r.ReadUInt32(); uint clientSeed = r.ReadUInt32(); ulong unk3 = r.ReadUInt64(); uint unk4 = r.ReadUInt32(); ulong unk5 = r.ReadUInt64(); byte[] clientDigest = r.ReadBytes(20); session.Account = IoC.Resolve <IAccountRepository>().FindByName(accountName); cryptor.SetSymmetricAlgorithm(new WowCryptRC4(session.Account.SessionKey)); if (!ByteArrayExtensions.Equals(clientDigest, ComputeServerDigest(clientSeed))) { throw new Exception(); } session.Send(GetAuthResponcePkt()); uint addonInfoBlockSize = r.ReadUInt32(); dataStream = new InflaterInputStream(dataStream); //дальше данные запакованы r = new BinaryReader(dataStream); try { while (true) { var addonInfo = new AddonInfo { Name = r.ReadCString(), Crc = r.ReadUInt64(), Status = r.ReadByte(), }; AddonManager.Instance[addonInfo.Name] = addonInfo; } } catch (Exception e) { } //_client.Send(GetAddonInfoPkt()); session.Send(GetTutorialFlagsPkt()); session.SendAccountDataTimes(0x15); }
private void Check16(ushort value, bool isLittleEndian = true) { var bytes = BitConverter.GetBytes(value); var bb = new byte[10]; if (isLittleEndian) { Array.Reverse(bytes); } Array.Copy(bytes, 0, bb, 2, 2); bytes = bb; var result = ByteArrayExtensions.ToUInt16(bytes, 2, isLittleEndian); Assert.AreEqual(value, result); }
internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = this.Algorithm.Write(buffer, dnsOffset, compressionData, offsetInDns); int offset1 = dnsOffset + offsetInDns + num; ByteArrayExtensions.Write(buffer, offset1, this.TimeSigned, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 6, this.Fudge, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 8, (ushort)this.MessageAuthenticationCode.Length, Endianity.Big); this.MessageAuthenticationCode.Write(buffer, offset1 + 10); int offset2 = offset1 + (10 + this.MessageAuthenticationCode.Length); ByteArrayExtensions.Write(buffer, offset2, this.OriginalId, Endianity.Big); ByteArrayExtensions.Write(buffer, offset2 + 2, (ushort)this.Error, Endianity.Big); ByteArrayExtensions.Write(buffer, offset2 + 4, (ushort)this.Other.Length, Endianity.Big); this.Other.Write(buffer, offset2 + 6); return(num + 16 + this.MessageAuthenticationCode.Length + this.Other.Length); }
internal override int WriteData(byte[] buffer, int dnsOffset, int offsetInDns, DnsDomainNameCompressionData compressionData) { int num = this.Algorithm.Write(buffer, dnsOffset, compressionData, offsetInDns); int offset1 = dnsOffset + offsetInDns + num; ByteArrayExtensions.Write(buffer, offset1, this.Inception.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 4, this.Expiration.Value, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 8, (ushort)this.Mode, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 10, (ushort)this.Error, Endianity.Big); ByteArrayExtensions.Write(buffer, offset1 + 12, (ushort)this.Key.Length, Endianity.Big); this.Key.Write(buffer, offset1 + 14); int offset2 = offset1 + 14 + this.Key.Length; ByteArrayExtensions.Write(buffer, offset2, (ushort)this.Other.Length, Endianity.Big); this.Other.Write(buffer, offset2 + 2); return(num + 16 + this.Key.Length + this.Other.Length); }
private HonoplayDbContext InitAndGetDbContext(out Guid tenantId, out int adminUserId) { var context = GetDbContext(); var salt = ByteArrayExtensions.GetRandomSalt(); var adminUser = new AdminUser { Id = 1, Email = "*****@*****.**", Password = "******".GetSHA512(salt), PasswordSalt = salt, LastPasswordChangeDateTime = DateTimeOffset.Now.AddDays(-5) }; context.AdminUsers.Add(adminUser); adminUserId = adminUser.Id; var tenant = new Tenant { Name = "testTenant", HostName = "localhost", CreatedBy = adminUserId }; context.Tenants.Add(tenant); context.TenantAdminUsers.Add(new TenantAdminUser { TenantId = tenant.Id, AdminUserId = adminUserId, CreatedBy = adminUserId }); context.Questions.Add(new Question { Duration = 3, Text = "testQuestion", CreatedBy = adminUserId, TenantId = tenant.Id }); tenantId = tenant.Id; context.SaveChanges(); return(context); }
public static void WritePacket(this Stream stream, byte[] bytes, int count, bool addCount) { if (addCount) { var countBytes = ByteArrayExtensions.GetBytes((int)count); var arr = new byte[count + 4]; Array.Copy(countBytes, arr, 4); Array.Copy(bytes, 0, arr, 4, count); stream.Write(arr, 0, count + 4); } else { stream.Write(bytes, 0, count); } }
internal override int WriteData(byte[] buffer, int offset) { ByteArrayExtensions.Write(buffer, offset, (byte)this.HostIdentityTag.Length); ByteArrayExtensions.Write(buffer, offset + 1, (byte)this.PublicKeyAlgorithm); ByteArrayExtensions.Write(buffer, offset + 2, (ushort)this.PublicKey.Length, Endianity.Big); this.HostIdentityTag.Write(buffer, offset + 4); int num1 = 4 + this.HostIdentityTag.Length; this.PublicKey.Write(buffer, offset + num1); int num2 = num1 + this.PublicKey.Length; foreach (DnsDomainName dnsDomainName in this.RendezvousServers) { dnsDomainName.WriteUncompressed(buffer, offset + num2); num2 += dnsDomainName.NonCompressedLength; } return(num2); }
/// <summary> /// Checks whether a byte array starts with a known header, containing the app name and an /// optional revision number. /// </summary> /// <param name="packedCipher">Byte array to examine.</param> /// <param name="expectedAppName">The header must start with this app name.</param> /// <param name="revision">reveives the revision number.</param> /// <returns>Returns true if the array starts with a valid header, otherwise false.</returns> public static bool HasMatchingHeader(byte[] packedCipher, string expectedAppName, out int revision) { if (packedCipher != null) { // test for app name if (ByteArrayExtensions.ContainsAt(packedCipher, CryptoUtils.StringToBytes(expectedAppName), 0)) { int position = expectedAppName.Length; // Followed by separator? if (ByteArrayExtensions.ContainsAt(packedCipher, (byte)Separator, position)) { revision = 1; return(true); } if (ByteArrayExtensions.ContainsAt(packedCipher, CryptoUtils.StringToBytes(RevisionSeparator), position)) { int digitsStart = position + RevisionSeparator.Length; int digitsEnd = digitsStart; // Skip digits while (ByteArrayExtensions.ContainsDigitCharAt(packedCipher, digitsEnd)) { digitsEnd++; } // Followed by separator? if ((digitsEnd > digitsStart) && (ByteArrayExtensions.ContainsAt(packedCipher, (byte)Separator, digitsEnd))) { byte[] digitsPart = new byte[digitsEnd - digitsStart]; Array.Copy(packedCipher, digitsStart, digitsPart, 0, digitsPart.Length); revision = int.Parse(CryptoUtils.BytesToString(digitsPart)); return(true); } } } } revision = 0; return(false); }