Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 4 additions & 10 deletions src/ImageSharp/Formats/Png/PngDecoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ internal sealed class PngDecoderCore
/// </summary>
private readonly byte[] buffer = new byte[4];

/// <summary>
/// Reusable CRC for validating chunks.
/// </summary>
private readonly Crc32 crc = new Crc32();

/// <summary>
/// The global configuration.
/// </summary>
Expand Down Expand Up @@ -1159,18 +1154,17 @@ private bool TryReadChunk(out PngChunk chunk)
/// <param name="chunk">The <see cref="PngChunk"/>.</param>
private void ValidateChunk(in PngChunk chunk)
{
uint crc = this.ReadChunkCrc();
uint inputCrc = this.ReadChunkCrc();

if (chunk.IsCritical)
{
Span<byte> chunkType = stackalloc byte[4];
BinaryPrimitives.WriteUInt32BigEndian(chunkType, (uint)chunk.Type);

this.crc.Reset();
this.crc.Update(chunkType);
this.crc.Update(chunk.Data.GetSpan());
uint validCrc = Crc32.Calculate(chunkType);
validCrc = Crc32.Calculate(validCrc, chunk.Data.GetSpan());

if (this.crc.Value != crc)
if (validCrc != inputCrc)
{
string chunkTypeName = Encoding.ASCII.GetString(chunkType);
PngThrowHelper.ThrowInvalidChunkCrc(chunkTypeName);
Expand Down
13 changes: 3 additions & 10 deletions src/ImageSharp/Formats/Png/PngEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@ internal sealed class PngEncoderCore : IDisposable
/// </summary>
private readonly byte[] chunkDataBuffer = new byte[16];

/// <summary>
/// Reusable CRC for validating chunks.
/// </summary>
private readonly Crc32 crc = new Crc32();

/// <summary>
/// The encoder options
/// </summary>
Expand Down Expand Up @@ -1120,18 +1115,16 @@ private void WriteChunk(Stream stream, PngChunkType type, byte[] data, int offse

stream.Write(this.buffer, 0, 8);

this.crc.Reset();

this.crc.Update(this.buffer.AsSpan(4, 4)); // Write the type buffer
uint crc = Crc32.Calculate(this.buffer.AsSpan(4, 4)); // Write the type buffer

if (data != null && length > 0)
{
stream.Write(data, offset, length);

this.crc.Update(data.AsSpan(offset, length));
crc = Crc32.Calculate(crc, data.AsSpan(offset, length));
}

BinaryPrimitives.WriteUInt32BigEndian(this.buffer, (uint)this.crc.Value);
BinaryPrimitives.WriteUInt32BigEndian(this.buffer, crc);

stream.Write(this.buffer, 0, 4); // write the crc
}
Expand Down
Loading