Axis
Axis

Reputation: 846

Speeding up Encryption

So this is how I am doing encryption right now:

public static byte[] Encrypt(byte[] Data, string Password, string Salt)
        {
            char[] converter = Salt.ToCharArray();
            byte[] salt = new byte[converter.Length];
            for (int i = 0; i < converter.Length; i++)
            {
                salt[i] = (byte)converter[i];
            }

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, salt);
            MemoryStream ms = new MemoryStream();
            Aes aes = new AesManaged();
            aes.Key = pdb.GetBytes(aes.KeySize / 8);
            aes.IV = pdb.GetBytes(aes.BlockSize / 8);
            CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);

            cs.Write(Data, 0, Data.Length); 
            cs.Close();

            return ms.ToArray();
        }

I am using this algorithm on data streaming over a network. The problem is it is a bit slow for what I am trying to do. So I was wondering if anyone has better way of doing it? I am no expert on encryption this method was pieced together from different sources. I am not entirely sure how it works.

I have clocked it at about 0.5-1.5ms and I need to get it down to about 0.1ms any ideas?

Upvotes: 0

Views: 2370

Answers (2)

Kennet Belenky
Kennet Belenky

Reputation: 2753

I'm pretty sure that performance is the least of your problems here.

Is the salt re-used for each packet? If so, you're using a strong cypher in a weak fashion. You're starting each packet with the cypher in exactly the same state. This is a security flaw. Someone skilled in cryptography would be able to crack your encryption after only a couple thousand packets.

I'm assuming you're sending a stream of packets to the same receiver. In that case, your use of AES will be much stronger if you keep the Aes object around and re-use it. That will make your use of the cypher much, much stronger and speed things up greatly.

As to the performance question, most of your time is being spent initializing the cypher. If you don't re-initialize it every time, you'll speed up quite a lot.

Upvotes: 4

Motomotes
Motomotes

Reputation: 4237

aes.KeySize>>3 would be faster than aes.KeySize / 8.

Upvotes: 0

Related Questions