public void Calculate_WithEmptyInput_ReturnsInit() { var calcualtor = new Crc32(0x04C11DB7, 0x00); var crc1 = calcualtor.Calculate(new byte[0]); var crc2 = calcualtor.Calculate(null); Assert.Equal <UInt32>(0, crc1); Assert.Equal <UInt32>(0, crc2); }
private static ITlvTag[] DecodePublicationString(string publicationString) { if (publicationString == null) { throw new ArgumentNullException(nameof(publicationString)); } byte[] dataBytesWithCrc32 = Base32.Decode(publicationString); // Length needs to be at least 13 bytes (8 bytes for time plus non-empty hash imprint plus 4 bytes for crc32) if (dataBytesWithCrc32 == null || dataBytesWithCrc32.Length < 13) { throw new TlvException("Publication string base 32 decode failed."); } byte[] dataBytes = Util.Clone(dataBytesWithCrc32, 0, dataBytesWithCrc32.Length - 4); byte[] computedCrc32 = Util.EncodeUnsignedLong(Crc32.Calculate(dataBytes, 0)); byte[] messageCrc32 = Util.Clone(dataBytesWithCrc32, dataBytesWithCrc32.Length - 4, 4); if (!Util.IsArrayEqual(computedCrc32, messageCrc32)) { throw new TlvException("Publication string CRC 32 check failed."); } byte[] hashImprint = Util.Clone(dataBytesWithCrc32, 8, dataBytesWithCrc32.Length - 12); byte[] publicationTimeBytes = Util.Clone(dataBytesWithCrc32, 0, 8); return(new ITlvTag[] { new IntegerTag(Constants.PublicationData.PublicationTimeTagType, false, false, Util.DecodeUnsignedLong(publicationTimeBytes, 0, publicationTimeBytes.Length)), new ImprintTag(Constants.PublicationData.PublicationHashTagType, false, false, new DataHash(hashImprint)) }); }
/// <summary> /// Converts a password into mail information. /// </summary> /// <param name="password">The password to convert.</param> /// <returns>Mail information from the password.</returns> public static WonderSMail Convert(string password) { if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } // Sanitaze and check password password = password.Replace(" ", ""); password = password.Replace("\t", ""); password = password.Replace(Environment.NewLine, ""); password = password.ToUpper(); if (password.Length != PasswordLength) { throw new ArgumentException("Invalid password length"); } // Do decryption rounds // The last byte for "scramble" is ignored. It should be the null // terminator 0x00. password = Permutation.Decrypt(password, false); byte[] binary = Substitution.Decrypt(password); Scramble.Decrypt(binary[0], binary, 4, binary.Length - 5); // Validate checksum uint crc32 = BitConverter.ToUInt32(binary, 0); uint newCrc32 = Crc32.Calculate(binary, 4, binary.Length - 5); if (crc32 != newCrc32) { throw new FormatException("Invalid crc32"); } // Convert the binary password into the structure. // Write the array into a stream to use the BitReader. DataStream stream = new DataStream(); stream.Write(binary, 4, binary.Length - 4); BitReader reader = new BitReader(stream); WonderSMail info = new WonderSMail(); info.MailType = reader.ReadByte(4); info.MissionType = reader.ReadByte(4); info.MissionSubType = reader.ReadByte(4); info.SourceClientId = reader.ReadUInt16(11); info.TargetClientId = reader.ReadUInt16(11); info.TargetClientFemale = reader.ReadUInt16(11); info.RewardObjectId = reader.ReadUInt16(10); info.RewardType = reader.ReadByte(4); info.RewardId = reader.ReadUInt16(11); info.RestrictionType = reader.ReadByte(1); info.RestrictionParam = reader.ReadUInt16(11); info.Random = reader.ReadUInt32(24); info.LocationId = reader.ReadByte(8); info.FloorNumber = reader.ReadByte(8); info.Requirement = reader.ReadByte(8); return(info); }
private static Suffix ReadSuffix(BinaryReader reader) { // this is the part of the file that the CRC is calculated on byte[] content = new byte[reader.BaseStream.Length - 4]; reader.BaseStream.Position = 0; reader.Read(content, 0, content.Length); byte[] suffixdata = new byte[Suffix.Size]; reader.BaseStream.Position = reader.BaseStream.Length - Suffix.Size; reader.Read(suffixdata, 0, Suffix.Size); var suffix = suffixdata.ToStruct <Suffix>(); // verify suffix if (suffix.dwCRC != Crc32.Calculate(content)) { throw new ArgumentException("The selected dfu file has invalid CRC."); } if (suffix.bLength < Suffix.Size) { throw new ArgumentException("The selected dfu file has invalid suffix length."); } if (suffix.sDfuSignature != Suffix.Signature) { throw new ArgumentException("The selected dfu file has invalid suffix signature."); } return(suffix); }
private void HandlePacket() { if (Message.Magic != MessageContainer.MagicNumber) { Program.Log($" Incorrect packet magic, is {Message.Magic:X08} but should be {MessageContainer.MagicNumber:X08}"); } if (Message.To != MessageContainer.ConnectionServer) { Program.Log($" Incorrect receiver id, is {Message.To:X08} but should be {MessageContainer.ConnectionServer:X08}"); } uint crc32 = Crc32.Calculate(Message.Payload); if (crc32 != Message.PayloadChecksum) { Program.Log($" Incorrect checksum, is {Message.PayloadChecksum:X08} but should be {crc32:X08}"); } Program.LogDebug(" === Packet received ==="); Program.LogDebug($" {nameof(Message.Magic)}: {Message.Magic:X08}"); Program.LogDebug($" {nameof(Message.From)}: {Message.From:X08}"); Program.LogDebug($" {nameof(Message.To)}: {Message.To:X08}"); Program.LogDebug($" {nameof(Message.Type)}: {Message.Type}"); Program.LogDebug($" {nameof(Message.Unknown1)}: {Message.Unknown1:X08}"); Program.LogDebug($" {nameof(Message.PayloadSize)}: {Message.PayloadSize}"); Program.LogDebug($" {nameof(Message.PayloadChecksum)}: {Message.PayloadChecksum:X08}"); Program.LogDebug($" {nameof(Message.Payload)}: {Serializer.DumpBytes(Message.Payload)}"); HandlePayload(); }
/// <summary> /// Validate a password by checking the checksum. /// </summary> /// <param name="password">Password to validate.</param> /// <returns><c>true</c> if the password is valid, <c>false</c> otherwise.</returns> public static bool ValidatePassword(string password) { if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException(nameof(password)); } // Sanitaze and check password password = password.Replace(" ", ""); password = password.Replace(Environment.NewLine, ""); password = password.ToUpper(); if (password.Length != PasswordLength) { throw new ArgumentException("Invalid password length"); } // Do decryption rounds byte[] binary; try { password = Permutation.Decrypt(password, false); binary = Substitution.Decrypt(password); Scramble.Decrypt(binary[0], binary, 4, binary.Length - 5); } catch { return(false); } // Validate checksum uint crc32 = BitConverter.ToUInt32(binary, 0); uint newCrc32 = Crc32.Calculate(binary, 4, binary.Length - 5); return(crc32 == newCrc32); }
public void CalculatesCorrectCrc32ForRosettaCodeExample() { var input = Encoding.ASCII.GetBytes("The quick brown fox jumps over the lazy dog"); var result = Crc32.Calculate(input); Assert.Equal("414fa339", result.ToString("X"), StringComparer.InvariantCultureIgnoreCase); }
protected void RunGeneratesCorrectChecksumForFirmware() { var bundle = new FirmwareBundle(); bundle.Load(ResourceManager.GetFirmwareBundle(), GetZip()); Assert.AreEqual(bundle.Manifest.Firmware.CRC, Crc32.Calculate(bundle.Firmware)); }
public void SingleByteValueCorrect() { const uint expected = 3523407757; var input = new byte[] { 0 }; Assert.Equal(expected, Crc32.Calculate(input)); }
public void GeneratesCorrectChecksumForApp() { var bundle = new AppBundle(); bundle.Load(ResourceManager.GetAppBundle(), new ZipImplementation()); Assert.AreEqual(bundle.Manifest.Application.CRC, Crc32.Calculate(bundle.App)); }
public void Calculate_Works() { var calcualtor = new Crc32(0x04C11DB7, 0xFFFFFFFF); var data = new byte[] { 0xDE, 0xAD, 0xBE, 0xEF }; var crc = calcualtor.Calculate(data); Assert.Equal <UInt32>(0x81DA1A18, crc); }
public void ByteValueCorrect() { const uint expected = 2711477844; var input = new byte[] { 0, 0, 177, 143 }; Assert.Equal(expected, Crc32.Calculate(input)); }
protected void RunGeneratesCorrectChecksumForFirmware() { var bundle = new FirmwareBundle(); bundle.Load(GetZip(), SoftwarePlatform.UNKNOWN); Assert.AreEqual(bundle.Manifest.Firmware.CRC, Crc32.Calculate(bundle.Firmware)); }
public void GeneratesCorrectChecksumForFirmware() { var bundle = new FirmwareBundle(); bundle.Load(ResourceManager.GetFirmwareBundle(), new ZipImplementation()); Assert.AreEqual(bundle.Manifest.Firmware.CRC, Crc32.Calculate(bundle.Firmware)); }
protected void RunGeneratesCorrectChecksumForApp() { var bundle = new AppBundle(); bundle.Load(GetZip(), SoftwarePlatform.UNKNOWN); Assert.AreEqual(bundle.Manifest.Application.CRC, Crc32.Calculate(bundle.App)); }
protected void RunGeneratesCorrectChecksumForApp() { var bundle = new AppBundle(); bundle.Load(ResourceManager.GetAppBundle(), GetZip()); Assert.AreEqual(bundle.Manifest.Application.CRC, Crc32.Calculate(bundle.App)); }
public void WriteLengthHash() { var oldPos = Position; Position = 0; WriteUInt32(Length - sizeof(uint)); WriteUInt32(Crc32.Calculate(this)); Position = oldPos; }
public static void AssertCrcMatches(byte[] buffer, uint expectedCrc) { uint actualCrc = Crc32.Calculate(buffer); if (actualCrc != expectedCrc) { throw new Exception(Resources.InvalidCRCMessage); } }
public void FromTwoPartsCorrect() { const uint expected = 2711477844; var input1 = new byte[] { 0, 0 }; var input2 = new byte[] { 177, 143 }; Assert.Equal(expected, Crc32.Calculate(input1, input2)); }
public List <Workflow> LoadByExternalId(string key) { var crc = Crc32.Calculate(key); Dictionary <Guid, Workflow> _dic = new Dictionary <Guid, Workflow>(); var mappingWorkflow = new WorkflowObjectMapping(_factory); var mappingEvent = new EventObjectMapping(_factory); var mappintAction = new ActionObjectMapping(); var workflows = _manager.Read <Workflow>("SELECT [Uuid], [ExternalId], [CreationDate], [LastUpdateDate], [WorkflowName], [WorkflowVersion], [Concurency] FROM [Workflows] WHERE [ExternalIdCrc] = @externalIdCrc AND [Closed] = 0" , mappingWorkflow , _manager.CreateParameter("externalIdCrc", System.Data.DbType.Int64, crc) ) .ToList(); if (workflows.Any()) { foreach (var item in workflows) { _dic.Add(item.Uuid, item); } var events = _manager.Read <EventByKey>("SELECT [Uuid], [WorkflowUuid], [Name], [CreationDate], [EventDate], [FromState], [ToState], [Datas], [DatasWorkflow] FROM [WorkflowEvents] WHERE [ExternalIdCrc] = @externalIdCrc AND [Closed] = 0 ORDER BY [ORDER]" , mappingEvent , _manager.CreateParameter("externalIdCrc", System.Data.DbType.Int64, crc) ).ToList(); Dictionary <Guid, Event> _dic2 = new Dictionary <Guid, Event>(); foreach (var item in events) { if (_dic.TryGetValue(item.WorkflowUuid, out Workflow w)) // prevent unfortunaly crc collision { w.Events.Add(item); _dic2.Add(item.Uuid, item); _factory.Serializer.Populate(w, item.Tag); } } var actions = _manager.Read <ActionByKey>("SELECT [Uuid], [EventUuid], [Name], [ExternalIdCrc], [Closed], [ExecuteMessage], [ResultExecuteMessage], [CancelExecuteMessage], [ResultCancelExecuteMessage] FROM [WorkflowActions] WHERE [ExternalIdCrc] = @externalIdCrc AND [Closed] = 0 ORDER BY [ORDER]" , mappintAction , _manager.CreateParameter("externalIdCrc", System.Data.DbType.Int64, crc) ).ToList(); foreach (var item in actions) { if (_dic2.TryGetValue(item.EventUuid, out Event e)) // prevent unfortunaly crc collision { e.Actions.Add(item); } } } return(workflows); }
private static void DispatchMsg(object Msg) { var MsgName = Msg.GetType().FullName; var MsgId = Crc32.Calculate(MsgName); if (MsgHandlerDic_.TryGetValue(MsgId, out var MsgListener)) { MsgListener.Trigger(Msg); } }
public static void UnRegisterMsgHandler <T>(LiteAction <T> Callback) where T : BaseNetMsg { string MsgName = typeof(T).FullName; uint MsgId = Crc32.Calculate(MsgName); if (MsgHandlerDic_.ContainsKey(MsgId)) { ((MsgListenerImpl <T>)MsgHandlerDic_[MsgId]).OnEvent -= Callback; } }
public void SetSeed(string seedText) { _seedText = seedText; WorldGen.currentWorldSeed = seedText; if (!int.TryParse(seedText, out _seed)) { _seed = Crc32.Calculate(seedText); } _seed = ((_seed == int.MinValue) ? int.MaxValue : Math.Abs(_seed)); }
public void SetSeed(string seedText) { this._seedText = seedText; WorldGen.currentWorldSeed = seedText; if (!int.TryParse(seedText, out this._seed)) { this._seed = Crc32.Calculate(seedText); } this._seed = this._seed == int.MinValue ? int.MaxValue : Math.Abs(this._seed); }
public void Calculate() { byte[] bytes = Encoding.ASCII.GetBytes( "The quick brown fox jumps over the lazy dog"); uint expected = BitConverter.ToUInt32( new byte[] { 0x39, 0xa3, 0x4f, 0x41, }, 0); Assert.Equal(expected, Crc32.Calculate(bytes)); }
public void MatchesReference(int length) { var data = GetBuffer(length); var crc = new SharpCrc32(); crc.Update(data); long expected = crc.Value; long actual = Crc32.Calculate(data); Assert.Equal(expected, actual); }
/// <summary> /// Converts a missiong information into a password. /// </summary> /// <param name="info">Mission to convert.</param> /// <returns>The password.</returns> public static string Convert(WonderSMail info) { if (info == null) { throw new ArgumentNullException(nameof(info)); } // Serialize the structure into a bit stream DataStream stream = new DataStream(); BitWriter writer = new BitWriter(stream); writer.Write(info.MailType, 4); writer.Write(info.MissionType, 4); writer.Write(info.MissionSubType, 4); writer.Write(info.SourceClientId, 11); writer.Write(info.TargetClientId, 11); writer.Write(info.TargetClientFemale, 11); writer.Write(info.RewardObjectId, 10); writer.Write(info.RewardType, 4); writer.Write(info.RewardId, 11); writer.Write(info.RestrictionType, 1); writer.Write(info.RestrictionParam, 11); writer.Write(info.Random, 24); writer.Write(info.LocationId, 8); writer.Write(info.FloorNumber, 8); writer.Write(info.Requirement, 8); // Write the stream into an array for the rounds. // We allocate an extra space for the checksum (first uint) // and the null terminator (last byte). byte[] binary = new byte[stream.Length + 5]; stream.Position = 0; stream.Read(binary, 4, (int)stream.Length); // Create checksum uint crc32 = Crc32.Calculate(binary, 4, binary.Length - 5); byte[] crc32Bytes = BitConverter.GetBytes(crc32); binary[0] = crc32Bytes[0]; binary[1] = crc32Bytes[1]; binary[2] = crc32Bytes[2]; binary[3] = crc32Bytes[3]; // Do encryption rounds // The key is the checksum, we don't encrypt the null terminator. Scramble.Encrypt(crc32Bytes[0], binary, 4, binary.Length - 5); string password = Substitution.Encrypt(binary, PasswordLength); password = Permutation.Encrypt(password, false); return(password); }
private bool CheckArchiveCrc() { var RawBuffer = ReadStream_.GetRawBuffer(); // Header foreach (var Ch in Header) { if (ReadStream_.ReadInt8() != (byte)Ch) { LLogger.LError("is invalid lite archive file"); return(false); } } // Version var VersionCode = ReadStream_.ReadInt32(); if (VersionCode < ForceVersionCode) { LLogger.LError($"force require version {ForceVersionCode}, current is {VersionCode}"); return(false); } if (VersionCode < CurrentVersionCode) { // compatible code } // Length var Length = ReadStream_.ReadInt32(); if (Length != RawBuffer.Length) { LLogger.LError($"error archive file length, expect : {Length}, but now : {RawBuffer.Length}"); return(false); } // Crc32 var CrcCode = ReadStream_.ReadUInt32(); var DataStart = Header.Length + 4 + 4 + 4; var DataLength = RawBuffer.Length - DataStart; var Code = Crc32.Calculate(RawBuffer, DataStart, DataLength); if (Code != CrcCode) { LLogger.LError("archive data is broken"); return(false); } return(true); }
public void GetOrAdd_UsesValueFromCache_IfGlobalHasNotChanged() { // Arrange var instance = new PreCompile(); var length = Encoding.UTF8.GetByteCount(instance.Content); var fileProvider = new TestFileProvider(); var lastModified = DateTime.UtcNow; var fileInfo = new TestFileInfo { Length = length, LastModified = lastModified, Content = instance.Content }; fileProvider.AddFile(ViewPath, fileInfo); var globalContent = "global-content"; var globalFileInfo = new TestFileInfo { Content = globalContent, LastModified = DateTime.UtcNow }; fileProvider.AddFile("_ViewImports.cshtml", globalFileInfo); var globalRazorFileInfo = new RazorFileInfo { Hash = Crc32.Calculate(GetMemoryStream(globalContent)).ToString(CultureInfo.InvariantCulture), HashAlgorithmVersion = 1, LastModified = globalFileInfo.LastModified, Length = globalFileInfo.Length, RelativePath = "_ViewImports.cshtml", FullTypeName = typeof(RuntimeCompileIdentical).FullName }; var precompiledViews = new ViewCollection(); precompiledViews.Add(globalRazorFileInfo); var cache = new CompilerCache(new[] { precompiledViews }, TestLoadContext, fileProvider); // Act var result = cache.GetOrAdd(ViewPath, compile: _ => { throw new Exception("shouldn't be invoked"); }); // Assert Assert.NotSame(CompilerCacheResult.FileNotFound, result); var actual = result.CompilationResult; Assert.NotNull(actual); Assert.Equal(typeof(PreCompile), actual.CompiledType); }
public static void RegisterMsgHandler <T>(LiteAction <T> Callback) where T : BaseNetMsg { string MsgName = typeof(T).FullName; uint MsgId = Crc32.Calculate(MsgName); MsgId2Name_[MsgId] = MsgName; if (!MsgHandlerDic_.ContainsKey(MsgId)) { MsgHandlerDic_.Add(MsgId, new MsgListenerImpl <T>()); } ((MsgListenerImpl <T>)MsgHandlerDic_[MsgId]).OnEvent += Callback; }
public void Write(TagContainer tagContainer, Stream input, Stream output) { if (input == null) { throw new ArgumentNullException("input"); } if (output == null) { throw new ArgumentNullException("output"); } if (tagContainer == null) { throw new ArgumentNullException("tagContainer"); } // // Validate whether the tag container is in ID3V2.3 formaz // string message; var isTagValid = ValidateTag(tagContainer, out message); if (!isTagValid) { throw new InvalidID3StructureException(message); } // // OK. ID3Tag is valid. Let's write the tag. // // Calculate the CRC32 value of the frameBytes ( before unsync!) // byte[] extendedHeaderBytes; var tagHeader = GetTagHeader(tagContainer); var frameBytes = GetFrameBytes(tagContainer); if (tagContainer.Tag.CrcDataPresent) { var crc32 = new Crc32(Crc32.DefaultPolynom); var crcValue = crc32.Calculate(frameBytes); tagContainer.Tag.SetCrc32(crcValue); } // // OK. Build the complete tag // byte[] tagBytes; var extendedHeaderLength = GetExtendedHeaderLength(tagContainer, out extendedHeaderBytes); var rawTagBytes = BuildTag(tagHeader, extendedHeaderBytes, frameBytes, tagContainer.Tag.PaddingSize); if (tagContainer.Tag.Unsynchronisation) { tagBytes = AddUnsyncBytes(rawTagBytes); } else { tagBytes = rawTagBytes; } // // encode the length // var length = tagBytes.LongLength -10; //if (tagContainer.Tag.ExtendedHeader) //{ // // Header + Size Coding. // length += extendedHeaderLength + 4; //} var bits = GetBitCoding(length); var lengthBytes = new byte[4]; EncodeLength(bits, lengthBytes); Array.Copy(lengthBytes, 0, tagBytes, 6, 4); // // Build the tag bytes and start writing. // if (!input.CanRead) { throw new ID3IOException("Cannot read input stream"); } if (!output.CanWrite) { throw new ID3IOException("Cannot write to output stream"); } WriteToStream(input, output, tagBytes); }
private static byte[] BuildId3V3Tag(TagContainer tagContainer) { byte[] tagBytes; var tag = tagContainer.GetId3V23Descriptor(); var frameBytes = GetFrameBytes(tagContainer); // // Calculate the CRC32 value of the frameBytes ( before unsync!) // if (tag.CrcDataPresent) { var crc32 = new Crc32(Crc32.DefaultPolynom); var crcValue = crc32.Calculate(frameBytes); tag.SetCrc32(crcValue); } // // OK. Build the complete tag // var extendedHeaderBytes = GetExtendedHeaderV3(tagContainer); var tagHeader = GetTagHeader(tagContainer); var rawTagBytes = BuildFinalTag(tagHeader, extendedHeaderBytes, frameBytes, tag.PaddingSize, false); if (tag.Unsynchronisation) { tagBytes = AddUnsyncBytes(rawTagBytes); } else { tagBytes = rawTagBytes; } return tagBytes; }