3

I have a Byte[] field that is a file contents that I need to encrypt. Nothing special or fancy, just enough to make sure the next person who gets it won't be able to easily decode it without some effort. I would use the encryption that comes with .Net Framework 4.0 but I definitely do not need to make the file any bigger than it is.

I thought about just simply reversing the array or adding a few bytes to the end...?

If I can avoid making the array to much bigger that would be great.

Any suggestions?

Thanks!

6
  • Why do you need this encryption? Commented Dec 21, 2010 at 16:11
  • Take a look at the answer to this question: stackoverflow.com/q/202011/50079. Commented Dec 21, 2010 at 16:11
  • possible duplicate of Encrypt/Decrypt string in .NET Commented Dec 21, 2010 at 16:14
  • I've voted for duplicate because it is basically the same. Before you can encrypt a string you have to convert it to a byte-array, which is pretty much this question. I also vote for the first answer on that question, RSA. Commented Dec 21, 2010 at 16:15
  • msdn.microsoft.com/en-us/library/… just an example... Commented Dec 21, 2010 at 16:15

2 Answers 2

13

Does the addition of 1-16 bytes hurt? AES will pad by default using the below method:

    private static void EncryptThenDecrypt(byte[] msg)
    {
        byte[] message = msg; // fill with your bytes

        if (message is null)
        {
            return;
        }

        byte[] encMessage; // the encrypted bytes
        byte[] decMessage; // the decrypted bytes - s/b same as message
        byte[] key;
        byte[] iv;

        using (SymmetricAlgorithm aes = Aes.Create())
        {
            if (aes is null)
            {
                iv = key = null;
                encMessage = Array.Empty<byte>();
            }
            else
            {
                aes.GenerateKey();
                aes.GenerateIV();
                key = aes.Key;
                iv = aes.IV;
                encMessage = EncryptBytes(aes, message);
            }
        }

        using (SymmetricAlgorithm aes = Aes.Create())
        {
            if (aes is null || key is null)
            {
                decMessage = Array.Empty<byte>();
            }
            else
            {
                aes.Key = key;
                aes.IV = iv;
                decMessage = DecryptBytes(aes, encMessage);
            }
        }

        Debug.Assert(message.SequenceEqual(decMessage), "Decrypted bytes do not match original bytes.");
    }

    private static byte[] EncryptBytes(SymmetricAlgorithm alg, byte[] message)
    {
        if (message is null)
        {
#pragma warning disable S1168 // Empty arrays and collections should be returned instead of null
            return null;
#pragma warning restore S1168 // Empty arrays and collections should be returned instead of null
        }

        if (message.Length == 0)
        {
            return message;
        }

        if (alg is null)
        {
            throw new ArgumentNullException(nameof(alg));
        }

        using (MemoryStream stream = new MemoryStream())
        using (ICryptoTransform encryptor = alg.CreateEncryptor())
        using (CryptoStream encrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
        {
            encrypt.Write(message, 0, message.Length);
            encrypt.FlushFinalBlock();
            return stream.ToArray();
        }
    }

    private static byte[] DecryptBytes(SymmetricAlgorithm alg, byte[] message)
    {
        if (message is null)
        {
#pragma warning disable S1168 // Empty arrays and collections should be returned instead of null
            return null;
#pragma warning restore S1168 // Empty arrays and collections should be returned instead of null
        }

        if (message.Length == 0)
        {
            return message;
        }

        if (alg is null)
        {
            throw new ArgumentNullException(nameof(alg));
        }

        using (MemoryStream stream = new MemoryStream())
        using (ICryptoTransform decryptor = alg.CreateDecryptor())
        using (CryptoStream encrypt = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
        {
            encrypt.Write(message, 0, message.Length);
            encrypt.FlushFinalBlock();
            return stream.ToArray();
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

How do I go about decrypting this once it is encrypted?
First, keep your Key and IV handy from when you created your SymmetricAlgorithm. Then use the DecryptBytes method I'm about to edit the answer to have.
2

Don't invent your own Encryption mechanism (i.e. Security by Obfuscation), use one of the classes provided by the framework.

2 Comments

If I have various sized files, wouldn't this significantly change the size of the array, making it much bigger than the original?
Any approach worth even doing is going to increase the size of the file some. What is the current size of the file, one route you could take is to simply compress the file. You woudln't have to advertise what you did to the file, it certaintly wouldn't increase the file size, it might even decrease the size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.