/// <summary> /// Reads an image from filepath and encrypts its pixel content (This does not encrypt the image header!) /// Refer MSDN article on BitmapData class for details about reading & writing pixes in an image. /// Link: https://msdn.microsoft.com/en-us/library/system.drawing.imaging.bitmapdata.aspx#Examples /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static Bitmap EncryptImage(this string filePath, CipherMode cipherMode) { try { Bitmap bmp = new Bitmap(Bitmap.FromFile(filePath)); // Pick image from file path // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * bmp.Height; byte[] contentBytes = new byte[bytes]; // Copy the content bytes into the array (This does not copy the image header!). System.Runtime.InteropServices.Marshal.Copy(ptr, contentBytes, 0, bytes); byte[] modifiedBytes = null; // Modify the bytes switch (cipherMode) { case CipherMode.CBC: modifiedBytes = BlockCipher.Encrypt(contentBytes, CipherMode.CBC); break; case CipherMode.ECB: modifiedBytes = BlockCipher.Encrypt(contentBytes, CipherMode.ECB); break; default: break; } _encryptedBytes = modifiedBytes; // Store the encrypted bytes in memory, for later use in decryption routine. _bytes = bytes; // Copy the modified values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(modifiedBytes, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); return(bmp); } catch (Exception ex) { throw ex; } }
public static Image DecryptImage(this Bitmap bmp, CipherMode cipherMode) { try { // Lock the bitmap's bits. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Fetch the bytes to modify from the content stored during encryption int bytes = _bytes; byte[] contentBytes = _encryptedBytes; // Copy the content bytes into the array (This does not copy the image header!). // System.Runtime.InteropServices.Marshal.Copy(ptr, contentBytes, 0, bytes); // Modify the bytes byte[] modifiedBytes = null; // Modify the bytes switch (cipherMode) { case CipherMode.CBC: modifiedBytes = BlockCipher.Decrypt(contentBytes, CipherMode.CBC); break; case CipherMode.ECB: modifiedBytes = BlockCipher.Decrypt(contentBytes, CipherMode.ECB); break; default: break; } // Copy the modified values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(modifiedBytes, 0, ptr, bytes); // Unlock the bits. bmp.UnlockBits(bmpData); return(bmp); } catch (Exception ex) { throw ex; } }