Search code examples
c#encryptionbouncycastle

Implementing TEA algorithm using BouncyCastle


I was trying to adapt Håvard Stranden example (http://ox.no/posts/rsa-using-bouncycastle) of a RSA algorithm using BouncyCastle into a TEA algorithm, using also the examples that come with BouncyCastle, and I made the following code to encrypt my string:

byte[] data = Encoding.UTF8.GetBytes("This is an encoding test!!!...");

TeaEngine e = new TeaEngine();
e.Init(true, new KeyParameter(Encoding.UTF8.GetBytes("MyPassword")));

int blockSize = e.GetBlockSize();

byte[] outBytes = new byte[data.Length];

List<byte> output = new List<byte>();
for (int chunkPosition = 0; chunkPosition < data.Length; chunkPosition += blockSize)
{
    int chunkSize = Math.Min(blockSize, data.Length - (chunkPosition * blockSize));
    if (e.IsPartialBlockOkay)
    {
            e.ProcessBlock(data, chunkPosition, outBytes, chunkPosition);
    }
    else
    {
            e.ProcessBlock(data, chunkPosition, outBytes, chunkPosition);
    }
}

Console.WriteLine("Encrypted: " + Encoding.UTF8.GetString(output.ToArray()));

But I always get an error. Any idea on how to implement it?

Thanks in advance

EDIT: Sorry about not posting the error log, but I posted this at a later hour and forgot about it

Here it goes: At e.Init(true, new KeyParameter(Encoding.UTF8.GetBytes("MyPassword"))); I get an "Index was outside the bounds of the array."


Solution

  • TEA uses a 128-bit key, which is 16 bytes. Use a password that is 16 bytes long (or use a key-derivation function to get a 16-byte key from a shorter password):

    e.Init(true, new KeyParameter(Encoding.UTF8.GetBytes("MyPassword123456")));