罪犯可以伪造上传文件的内容类型。因此,如果我通过我的页面在服务器上接收文件,我不能仅检查其MIME类型和文件扩展名。有没有可靠的方法来检查上传的文件是否实际上是JPEG、GIF或PNG?我需要拒绝所有其他格式。我可以尝试逐位读取文件,但我要找什么呢?感谢任何建议或想法!
您可以尝试使用Bitmap.FromStream(stream)
在try-catch中解析上传图像的流。如果失败,说明它不是真正的图像。虽然这被认为是“异常编码”,但在这种情况下,实际上您正在寻找一个异常。
最简单的方法是检查输入流的头部并寻找特定的标识:
ASP.NET示例:
bool isValid = false;
char[] header = new char[10];
StreamReader sr = new StreamReader(Request.InputStream);
sr.Read(header, 0, 10);
// check if JPG
if (header[0] == 0xFF && header[1] == 0xD8)
{
isValid = true;
}
// check if GIF
else if (header[0] == 'G' && header[1] == 'I' && header[2] == 'F')
{
isValid = true;
}
// check if PNG
else if (header[0] == 137 && header[1] == 80 && header[2] == 78 && header[3] == 71 && header[4] == 13 && header[5] == 10 && header[6] == 26 && header[7] == 10)
{
isValid = true;
}