How to encrypt Bitmap image in c#

Category > CSHARP || Published on : Sunday, September 21, 2014 || Views: 15211 || encrypt Bitmap image in c#


In this post I will show you how to encrypt bitmap image in c#. The technique is very simple.

First we extract header from the image and then encrypt the rest byte data and then combined the header with this encrypted data.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Enc
{
    class Program
    {
        static string FILENAME = @"D:\ub.bmp";
        static string ENCFILENAME = @"D:\enc.bmp";
        static void Main(string[] args)
        {
            //Create instance of DES
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            //Generate IV and Key
            des.GenerateIV();
            des.GenerateKey();
            //Set Encryption mode
            des.Mode = CipherMode.ECB;
            //Read
            FileStream fileStream = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
            MemoryStream ms = new MemoryStream();
            fileStream.CopyTo(ms);
            //Store header in byte array (we will used this after encryption)
            var header = ms.ToArray().Take(54).ToArray();
            //Take rest from stream
            var imageArray = ms.ToArray().Skip(54).ToArray();
            //Create encryptor
            var enc = des.CreateEncryptor();
            //Encrypt image
            var encimg = enc.TransformFinalBlock(imageArray, 0, imageArray.Length);
            //Combine header and encrypted image
            var image = Combine(header, encimg);
            //Write encrypted image to disk
            File.WriteAllBytes(ENCFILENAME, image);


        }
        public static byte[] Combine(byte[] first, byte[] second)
        {
            byte[] ret = new byte[first.Length + second.Length];
            Buffer.BlockCopy(first, 0, ret, 0, first.Length);
            Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
            return ret;
        }
    }
}


Conclusion:-
So In this tutorial, We are going to learn How to encrypt Bitmap image in c#  with example. Happy Coding!!!!

Download Source Codes