Найти хэш-код изображения с помощью алгоритма MD5 и после загрузки того же изображения из браузера снова сгенерировать тC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Гость
 Найти хэш-код изображения с помощью алгоритма MD5 и после загрузки того же изображения из браузера снова сгенерировать т

Сообщение Гость »


i working on document authentication project. this is a asp.net C# webform project. firstly i upload the image and do some process on it. i add the qr code on the image like adding the watermark after that find the hash code of a image using md5 algorithm. and save the image with qr code in folder and also database. after that i download the same image with qr that i already uploaded and again find the hash code of the image and i got different hash code. now what i need to do, to get the same hash code of the image?

UploadDocument.aspx.cs

Код: Выделить всё

`using System; using System.Configuration; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Security.Cryptography; using System.Text; using System.Web.UI; using QRCoder; public partial class User_UploadDocument : System.Web.UI.Page {     SqlConnection con;     SqlCommand cmd;     string id;     string name;     string email;     string photo;     BasicCode b = new BasicCode();     protected void Page_Load(object sender, EventArgs e)     {     }     protected void btnupload_Click(object sender, EventArgs e)     {         if (fudoc.HasFile)         {             using (Stream stream = fudoc.PostedFile.InputStream)             {                 byte[] fileBytes = ReadFully(stream); // Get the byte array of the uploaded file                 // Generate hash code for the uploaded image                 string uploadedHash = ComputeFileHash(fileBytes);                 // Your existing code for processing the uploaded file and storing the hash code                 con = new SqlConnection(ConfigurationManager.AppSettings["LIS"]);                 cmd = new SqlCommand();                 con.Open();                 cmd.CommandText = "Select id, name, email, photo From Registration where id=@id";                 cmd.Parameters.AddWithValue("@id", Session["id"]);                 cmd.Connection = con;                 SqlDataReader dr = cmd.ExecuteReader();                 if (dr.Read())                 {                     id = dr["id"].ToString();                     name = dr["name"].ToString();                     email = dr["email"].ToString();                     photo = dr["photo"].ToString();                 }                 con.Close();                 DateTime dateTime = DateTime.Today;                 string date = dateTime.ToString("yyyy-MM-dd");                 con = new SqlConnection(ConfigurationManager.AppSettings["LIS"]);                 cmd = new SqlCommand();                 con.Open();                 cmd.CommandText = @"Insert Into Documents (did,id,document_type,doc_name_original,doc_name_qr,doc_with_qr_hashcode,qr_code,date)                                     Values (@did, @id, @dt, @dno, @dnq, @dwqhc, @qr, @date)";                 cmd.Parameters.AddWithValue("@did", b.generateID("did", "Documents"));                 cmd.Parameters.AddWithValue("@id", id);                 cmd.Parameters.AddWithValue("@dt", txtdocumentname.Text);                 cmd.Parameters.AddWithValue("@date", dateTime.Date);                 // Generate QR code                 string qrData = $"{txtdocumentname.Text}\n{name}\n{email}\n{photo}";                 QRCodeGenerator qr = new QRCodeGenerator();                 QRCodeData data = qr.CreateQrCode(qrData, QRCodeGenerator.ECCLevel.Q);                 QRCode code = new QRCode(data);                 // Convert QR code to a bitmap                 Bitmap bmp = code.GetGraphic(5);                 // Save QR code image                 string qrimgname = "QRCode_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";                 string qrpath = Server.MapPath("QR_Code/") + qrimgname;                 bmp.Save(qrpath, System.Drawing.Imaging.ImageFormat.Png);                 // Here We will upload image with QR code                 string fileName = Guid.NewGuid() + Path.GetExtension(fudoc.PostedFile.FileName);                 System.Drawing.Image upImage = System.Drawing.Image.FromStream(fudoc.PostedFile.InputStream);                 // Draw QR code onto the uploaded image                 using (Graphics g = Graphics.FromImage(upImage))                 {                     // Draw QR code onto the uploaded image at specified coordinates                     g.DrawImage(bmp, new PointF(0, 0));                     upImage.Save(Path.Combine(Server.MapPath("ImageWithQR"), fileName));                 }                 // Compute MD5 hash of the image                 byte[] imageBytes;                 using (MemoryStream ms = new MemoryStream())                 {                     upImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);                     imageBytes = ms.ToArray();                 }                 using (MD5 md5 = MD5.Create())                 {                     byte[] hashBytes = md5.ComputeHash(imageBytes);                     // Convert byte array to hex string (hash code)                     StringBuilder sb = new StringBuilder();                     for (int i = 0; i < hashBytes.Length;  i++)                     {                         sb.Append(hashBytes[i].ToString("x2")); // "x2" means lowercase hexadecimal                     }                     // Store the hash code in the database parameter                     cmd.Parameters.AddWithValue("@dwqhc", sb.ToString());                 }                 // Doc Original Name                 string Afileextention = System.IO.Path.GetExtension(fudoc.FileName);                 string aname = "Document-" + b.generateID("did", "Documents") + Afileextention;                 string axpath = Server.MapPath("Documents/") + aname;                 fudoc.SaveAs(axpath);                 cmd.Parameters.AddWithValue("@dno", aname);                 cmd.Parameters.AddWithValue("@dnq", fileName);                 cmd.Parameters.AddWithValue("@qr", qrimgname);                 cmd.Connection = con;                 int n = cmd.ExecuteNonQuery();                 con.Close();                 if (n > 0)                 {                     string script = @"                                 Swal.fire({                                   title: 'Your Document Uploaded Successfully!',                                   text: 'click ok button to continue!',                                   icon: 'success'                                 });                              ";                     ScriptManager.RegisterStartupScript(this, GetType(), "ShowAlert", script, false);                 }             }         }         else         {             string script = @"                                 Swal.fire({                                   title: 'Please Upload the file!',                                   text: 'click ok button to continue!',                                   icon: 'error'                                 });                              ";             ScriptManager.RegisterStartupScript(this, GetType(), "ShowAlert", script, false);         }     }     // Method to compute hash code of a file     private string ComputeFileHash(byte[] data)     {         using (MD5 md5 = MD5.Create())         {             byte[] hashBytes = md5.ComputeHash(data);             // Convert byte array to hex string             StringBuilder sb = new StringBuilder();             for (int i = 0; i < hashBytes.Length; i++)             {                 sb.Append(hashBytes[i].ToString("x2")); // "x2" means lowercase hexadecimal             }             return sb.ToString();         }     }     // Method to read stream into a byte array     private byte[] ReadFully(Stream input)     {         using (MemoryStream ms = new MemoryStream())         {             input.CopyTo(ms);             return ms.ToArray();         }     } } ` 
AuthenticateDocument.aspx.cs

Код: Выделить всё

`using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; using System.Data.SqlClient; public partial class User_AuthenticateDocument : System.Web.UI.Page {     SqlConnection con;     SqlCommand cmd;     protected void Page_Load(object sender, EventArgs e)     {     }     protected void btnupload_Click(object sender, EventArgs e)     {         if (fudoc.HasFile)         {             using (Stream stream = fudoc.PostedFile.InputStream)             {                 byte[] fileBytes = ReadFully(stream);  // Get the byte array of the uploaded file                 // Generate hash code for the uploaded image                 string uploadedHash = ComputeFileHash(fileBytes);                 // Check if the hash code exists in the database                 if (HashExistsInDatabase(uploadedHash))                 {                     string script = @"                                     Swal.fire({                                       title: 'Your Document is Authenticate!',                                       text: 'click ok button to continue!',                                       icon: 'success'                                     });                                  ";                     ScriptManager.RegisterStartupScript(this, GetType(), "ShowAlert", script, false);                 }                 else                 {                     string script = @"                                     Swal.fire({                                       title: 'Your Document is not Authenticate!',                                       text: 'click ok button to continue!',                                       icon: 'error'                                     });                                  ";                     ScriptManager.RegisterStartupScript(this, GetType(), "ShowAlert", script, false);                 }             }         }         else         {             string script = @"                                 Swal.fire({                                   title: 'Please Upload the file!',                                   text: 'click ok button to continue!',                                   icon: 'error'                                 });                              ";             ScriptManager.RegisterStartupScript(this, GetType(), "ShowAlert", script, false);         }     }     // Method to read fully from a stream and convert to byte array     private byte[] ReadFully(Stream input)     {         using (MemoryStream ms = new MemoryStream())         {             input.CopyTo(ms);             return ms.ToArray();         }     }     // Method to compute hash code of a file from byte array     private string ComputeFileHash(byte[] data)     {         using (MD5 md5 = MD5.Create())         {             byte[] hashBytes = md5.ComputeHash(data);             // Convert byte array to hex string             StringBuilder sb = new StringBuilder();             for (int i = 0; i < hashBytes.Length; i++)             {                 sb.Append(hashBytes[i].ToString("x2")); // "x2" means lowercase hexadecimal             }             return sb.ToString();         }     }     // Method to check if hash code exists in the database     private bool HashExistsInDatabase(string uploadedHash)     {         using (con = new SqlConnection(ConfigurationManager.AppSettings["LIS"]))         {             using (cmd = new SqlCommand())             {                 cmd.Connection = con;                 con.Open();                 cmd.CommandText = @"SELECT COUNT(*) FROM Documents WHERE doc_with_qr_hashcode = @HashCode";                 cmd.Parameters.AddWithValue("@HashCode", uploadedHash);                 int count = (int)cmd.ExecuteScalar();                 return count > 0;             }         }     } }` 
when i download the same image from browser i need the same hash code that i find previously.


Источник: https://stackoverflow.com/questions/781 ... ng-the-sam
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Есть ли способ ускорить мой код, чтобы найти хэш md5, начинающийся с нулей?
    Anonymous » » в форуме C#
    0 Ответы
    13 Просмотры
    Последнее сообщение Anonymous
  • Есть ли способ ускорить мой код, чтобы найти хэш md5, начинающийся с нулей?
    Anonymous » » в форуме C#
    0 Ответы
    11 Просмотры
    Последнее сообщение Anonymous
  • С++ получить хэш md5 встроенного ресурса
    Гость » » в форуме C++
    0 Ответы
    23 Просмотры
    Последнее сообщение Гость
  • При использовании md5 и implode для HTML-формы – почему хэш передается по POST [закрыто]
    Anonymous » » в форуме Php
    0 Ответы
    32 Просмотры
    Последнее сообщение Anonymous
  • Преобразование массива хэш-байтов md5 в строку
    Anonymous » » в форуме C#
    0 Ответы
    20 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»