Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. System.Security.Cryptography for encrypting binary files (not plain text)

System.Security.Cryptography for encrypting binary files (not plain text)

Scheduled Pinned Locked Moved C#
csharpsecurityc++graphicsalgorithms
6 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    Cyrilix
    wrote on last edited by
    #1

    Is there a way to use the .NET cryptography library to encrypt binary files as opposed to plain text files? I've been having a few issues with the way that encrypted bytes are decrypted back to their original state. What I do to initialize my algorithm for decryption is approximately the following:

    UnicodeEncoding byteConverter = new UnicodeEncoding();
    RijndaelManaged algorithm = new RijndaelManaged();
    algorithm.IV = byteConverter->GetBytes(/*a unicode string converted to bytes for init vector*/);
    algorithm.Key = byteConverter->GetBytes(/*a unicode string converted to bytes for password*/);
    return alg; //returned as base class "SymmetricAlgorithm"

    In order to encrypt, first, I call that stub of algorithm initialization code. Then I do approximately the following with a Byte[] data that I want to encrypt:

    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
    for (int i = 0; i < numBytes; i++)
    {
    cs.WriteByte(data[i]);
    }
    cs.FlushFinalBlock();
    byte encoded[] = ms.ToArray();
    cs.Close();
    ms.Close();
    string output = Convert.ToBase64String(encoded);

    In order to decrypt, first, I call that stub of algorithm initialization code. Then I do approximately the following with a string input that I want to decrypt:

    byte[] encoded = Convert.FromBase64String(input);
    MemoryStream ms = new MemoryStream(encoded);
    CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Read);
    byte decoded[] = new byte[encoded.Length];
    for (int i = 0; i < decoded.Length; i++)
    {
    int readByte = cs.ReadByte();
    if (readByte != -1)
    {
    decoded[i] = (byte)readByte;
    }
    }
    cs.Close();
    ms.Close();

    The problem is that if I call Encrypt, then Decrypt, encryption leaves me with a nice base64 string, which decrypt easily converts back to a byte array. But when I read the CryptoStream and get check all the values of int readByte everytime I read a byte, as soon as I come to the null-terminated character (0 ''), everything else that I read after that is the same garbage symbol (-51 'Í'). More precisely, the code that I'm writing here is the C# equivalent of my Managed C++ code (however, the problem does not lie in the unmanaged part or the unmanaged/managed conversion). So, to rephrase what I mean, say that I'm checking all the values of readByte for i = 0 to the length of the decoded b

    E 1 Reply Last reply
    0
    • C Cyrilix

      Is there a way to use the .NET cryptography library to encrypt binary files as opposed to plain text files? I've been having a few issues with the way that encrypted bytes are decrypted back to their original state. What I do to initialize my algorithm for decryption is approximately the following:

      UnicodeEncoding byteConverter = new UnicodeEncoding();
      RijndaelManaged algorithm = new RijndaelManaged();
      algorithm.IV = byteConverter->GetBytes(/*a unicode string converted to bytes for init vector*/);
      algorithm.Key = byteConverter->GetBytes(/*a unicode string converted to bytes for password*/);
      return alg; //returned as base class "SymmetricAlgorithm"

      In order to encrypt, first, I call that stub of algorithm initialization code. Then I do approximately the following with a Byte[] data that I want to encrypt:

      MemoryStream ms = new MemoryStream();
      CryptoStream cs = new CryptoStream(ms, algorithm.CreateEncryptor(), CryptoStreamMode.Write);
      for (int i = 0; i < numBytes; i++)
      {
      cs.WriteByte(data[i]);
      }
      cs.FlushFinalBlock();
      byte encoded[] = ms.ToArray();
      cs.Close();
      ms.Close();
      string output = Convert.ToBase64String(encoded);

      In order to decrypt, first, I call that stub of algorithm initialization code. Then I do approximately the following with a string input that I want to decrypt:

      byte[] encoded = Convert.FromBase64String(input);
      MemoryStream ms = new MemoryStream(encoded);
      CryptoStream cs = new CryptoStream(ms, algorithm.CreateDecryptor(), CryptoStreamMode.Read);
      byte decoded[] = new byte[encoded.Length];
      for (int i = 0; i < decoded.Length; i++)
      {
      int readByte = cs.ReadByte();
      if (readByte != -1)
      {
      decoded[i] = (byte)readByte;
      }
      }
      cs.Close();
      ms.Close();

      The problem is that if I call Encrypt, then Decrypt, encryption leaves me with a nice base64 string, which decrypt easily converts back to a byte array. But when I read the CryptoStream and get check all the values of int readByte everytime I read a byte, as soon as I come to the null-terminated character (0 ''), everything else that I read after that is the same garbage symbol (-51 'Í'). More precisely, the code that I'm writing here is the C# equivalent of my Managed C++ code (however, the problem does not lie in the unmanaged part or the unmanaged/managed conversion). So, to rephrase what I mean, say that I'm checking all the values of readByte for i = 0 to the length of the decoded b

      E Offline
      E Offline
      Ennis Ray Lynch Jr
      wrote on last edited by
      #2

      Skip the base 64 string part. Since you are using a binary file you should be using a FileStream or some other stream. I have never had any trouble encrypting streams.

      Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
      Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
      Most of this sig is for Google, not ego.

      C 1 Reply Last reply
      0
      • E Ennis Ray Lynch Jr

        Skip the base 64 string part. Since you are using a binary file you should be using a FileStream or some other stream. I have never had any trouble encrypting streams.

        Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
        Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
        Most of this sig is for Google, not ego.

        C Offline
        C Offline
        Cyrilix
        wrote on last edited by
        #3

        Well, base64 is easily encoded in a string, or a MemoryStream (which is what I'm using). What I'm essentially doing afterwards when I write to a file is actually saving the base64 encoded string directly to the file like I save text. Thanks for the FileStream suggestion... maybe that's also a plausible implementation. Also, I've toyed around with the idea of doing multiple base64 conversions, so converting a binary file to base64 first, then encrypting, then encoding to base64 again. After every base64 transform step, I'm able to again fit the entire "data" of the file into an ANSI string.

        C 1 Reply Last reply
        0
        • C Cyrilix

          Well, base64 is easily encoded in a string, or a MemoryStream (which is what I'm using). What I'm essentially doing afterwards when I write to a file is actually saving the base64 encoded string directly to the file like I save text. Thanks for the FileStream suggestion... maybe that's also a plausible implementation. Also, I've toyed around with the idea of doing multiple base64 conversions, so converting a binary file to base64 first, then encrypting, then encoding to base64 again. After every base64 transform step, I'm able to again fit the entire "data" of the file into an ANSI string.

          C Offline
          C Offline
          Cyrilix
          wrote on last edited by
          #4

          I just figured out the issue, and it had nothing to do with the CryptoStream. I was simply deceived and made the wrong assumptions. In the end, it was because I never opened the file in binary mode, so it was being parsed as a string.

          G A 2 Replies Last reply
          0
          • C Cyrilix

            I just figured out the issue, and it had nothing to do with the CryptoStream. I was simply deceived and made the wrong assumptions. In the end, it was because I never opened the file in binary mode, so it was being parsed as a string.

            G Offline
            G Offline
            Guffa
            wrote on last edited by
            #5

            You have a binary file, and the crypto stream only encrypts or decrypts binary data. There is no reason at all to turn the data into a string. ;) As I always say:

            Despite everything, the person most likely to be fooling you next is yourself.

            1 Reply Last reply
            0
            • C Cyrilix

              I just figured out the issue, and it had nothing to do with the CryptoStream. I was simply deceived and made the wrong assumptions. In the end, it was because I never opened the file in binary mode, so it was being parsed as a string.

              A Offline
              A Offline
              ajtunbridge
              wrote on last edited by
              #6

              This is a little library I use. I pulled it together from various sources and stake no claim to it. It will encrypt binary and strings using public/private key encryption and standard passphrase encryption. Hope it's of some help. Crptography.zip[^]

              1 Reply Last reply
              0
              Reply
              • Reply as topic
              Log in to reply
              • Oldest to Newest
              • Newest to Oldest
              • Most Votes


              • Login

              • Don't have an account? Register

              • Login or register to search.
              • First post
                Last post
              0
              • Categories
              • Recent
              • Tags
              • Popular
              • World
              • Users
              • Groups