How to 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;
        }
    }
}

Comments

Popular posts from this blog

Bootstrap Modal Popup keep open on PostBack in ASP.Net

Resolved Issue in Asp core 3.0 serializersettings does not exist in AddJsonOptions

.Net most asked interview questions for experienced professionals (C#,Asp WEBFORM,MVC,ASP CORE,WEB API,SQL Server,Java Script,Jquery)