Search code examples
c#encryptionheaderbmp

Remove bmp header to encrypt


I'm pretty new to C# and got handed this AES encryption project on images. There's probably a very simple thing that I'm missing here. I'm trying to remove the header from a bmp and encrypt the rest then add the header back. If I don't remove the header the program works well. To remove, I tried this (bmp header is 54 bytes):

MyImage = new Bitmap("path");
MemoryStream ms = new MemoryStream();

MyImage.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

byte[] Header=null, picture=null, pictureFull = ms.ToArray();


for (int i = 0; i < pictureFull.Length; i++)
{
    if (i < 54)
    { Header[i] = pictureFull[i]; }
    else 
    { picture[i - 54] = pictureFull[i]; }
}


byte[] demoKeyBytes = new byte[] {  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};

PaddingMode padding = PaddingMode.ISO10126;

EncryptedImg = EncryptCall(demoKeyBytes, padding, picture);

The problem is that if i try to go on and encrypt and decrypt "picture" I get a null value. I also get a null value if i go on to enc/dec with the full image "pictureFull". I need to completely remove the FOR in order for the program to enc/dec normally "pictureFull", although that FOR doesn't even modify it. Is there some other way to save byte[] arrays or what's wrong?


Solution

  • byte[] is an object, so you don't want to initialize a variable of that type to null. You probably want to initialize Header like this:

    byte[] Header = new byte[54];
    

    and picture to a new byte[] with length at least equal to the actual image data length, like this:

    byte[] picture = new byte[pictureFull.Length - 54];
    

    Then you can copy things to them.