-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSignature.cs
More file actions
68 lines (60 loc) · 2.19 KB
/
Copy pathFileSignature.cs
File metadata and controls
68 lines (60 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
namespace SmartFileKit.Detection
{
/// <summary>
/// Represents a magic bytes signature used for detecting file types.
/// </summary>
public class FileSignature
{
/// <summary>
/// Gets the expected sequence of magic bytes.
/// </summary>
public byte[] MagicBytes { get; }
/// <summary>
/// Gets the start offset in the stream/buffer where the signature resides.
/// </summary>
public int Offset { get; }
/// <summary>
/// Gets the optional bitmask applied to the checked bytes.
/// </summary>
public byte[] Mask { get; }
/// <summary>
/// Initializes a new instance of the <see cref="FileSignature"/> class.
/// </summary>
/// <param name="magicBytes">The magic bytes sequence.</param>
/// <param name="offset">The starting byte index of the signature.</param>
/// <param name="mask">The optional bitmask.</param>
public FileSignature(byte[] magicBytes, int offset = 0, byte[] mask = null)
{
MagicBytes = magicBytes ?? throw new ArgumentNullException(nameof(magicBytes));
Offset = offset;
Mask = mask;
}
/// <summary>
/// Determines whether the given buffer matches this signature.
/// </summary>
/// <param name="buffer">The file byte buffer to check.</param>
/// <returns>True if the buffer matches the signature; otherwise, false.</returns>
public bool Matches(byte[] buffer)
{
if (buffer == null || buffer.Length < Offset + MagicBytes.Length)
return false;
for (int i = 0; i < MagicBytes.Length; i++)
{
byte fileByte = buffer[Offset + i];
byte magicByte = MagicBytes[i];
if (Mask != null && Mask.Length > i)
{
if ((fileByte & Mask[i]) != magicByte)
return false;
}
else
{
if (fileByte != magicByte)
return false;
}
}
return true;
}
}
}