C# 图片防篡改
1.逻辑:在读取图片文件流后,添加自己的加密签名信息,然后再保存文件,读取时截取对应的字节长度,以相同的方式转换成字符串并对比,确认图片是否更改
2. 加密方法
/// <summary> /// MD5: 加密方式 /// </summary> public static string MD5Hash(string input) { using (var md5 = MD5.Create()) { var result = md5.ComputeHash(Encoding.ASCII.GetBytes(input)); var strResult = BitConverter.ToString(result); return strResult.Replace("-", ""); } }
3.添加自定义签名信息
/// <summary> /// 图片加密签名 /// </summary> public static void ImageAddMD5Hash() { var str = "QWERTYUIOP"; // 签名 var md5ste = MD5Hash(str); string path = $"{AppDomain.CurrentDomain.BaseDirectory}"; string url = $"{path}File/Page4.png"; // 图片文件 MemoryStream stream1 = new MemoryStream(); using (FileStream stream = new FileStream(url, FileMode.Open, FileAccess.Read,FileShare.Read)) { var dd = Encoding.Unicode.GetBytes(md5ste); //byte[] strbytes = new byte[dd.Length]; byte[] bytes = new byte[stream.Length+dd.Length]; stream.Read(bytes, 0, (int)stream.Length); Array.Copy(dd,0, bytes, stream.Length, 64); Console.WriteLine(stream1.Length); FileStream fs = new FileStream($"{path}File/Page6.png", FileMode.Create); // 加密后的图片 fs.Write(bytes, 0, bytes.Length); fs.Dispose(); } }
4. 获取图片加密信息
/// <summary> /// 图片获得加密签名信息 /// </summary> public static void ImageGetMD5Hash() { string path = $"{AppDomain.CurrentDomain.BaseDirectory}"; string url = $"{path}File/Page4.png"; // 图片文件 var stream = File.OpenRead(url); MemoryStream memoryStream = new MemoryStream(); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); //byte[] bytes = new byte[16]; byte[] strbytes = new byte[64]; Array.Copy(bytes, bytes.Length - 64, strbytes, 0, 64); var str = Encoding.Unicode.GetString(strbytes); // 加密的信息 Console.WriteLine(str); stream.Dispose(); }