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(); } } } `
Код: Выделить всё
`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; } } } }`
Источник: https://stackoverflow.com/questions/781 ... ng-the-sam