C method of determining whether an uploaded file is an image to prevent Trojan uploading
- 2020-06-23 01:49:42
- OfStack
A lot of times trojans are uploaded to websites disguised as files in other formats, the most common being image formats. This paper takes C# as an example to describe the method of C# to determine whether the uploaded file is an image to prevent Trojan uploading. The specific method is as follows:
Method 1: Use the image object to determine if it is an image
/// <summary>
/// Determine if the file is an image
/// </summary>
/// <param name="path"> The full path to the file </param>
/// <returns> Returns the result </returns>
public Boolean IsImage(string path)
{
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(path);
return true;
}
catch (Exception e)
{
return false;
}
}
Method 2, determine the header
/// <summary>
/// Determine the type of file being uploaded based on the file header
/// </summary>
/// <param name="filePath">filePath Is the full path to the file </param>
/// <returns> return true or false</returns>
private bool IsPicture(string filePath)
{
try
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fs);
string fileClass;
byte buffer;
buffer = reader.ReadByte();
fileClass = buffer.ToString();
buffer = reader.ReadByte();
fileClass += buffer.ToString();
reader.Close();
fs.Close();
if (fileClass == "255216" || fileClass == "7173" || fileClass == "13780" || fileClass == "6677")
//255216 is jpg;7173 is gif;6677 is BMP,13780 is PNG;7790 is exe,8297 is rar
{
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
The tests show that method 2 works with trojans that modify their extensions directly, such as.asp to.jpg. However, jpg Trojans, which are generated by tools, have no effect. The first method is recommended at this time.