Search code examples
c#blowfish

Blowfish Invalid Length Exception


I'm encrypting my file with Blowfish algorithm but it seems that I don't know something about it. Whenever I try to Encipher() it will throw an exception that says 'Invalid Length'. I figured that the length must be zero when it's getting mod with 8 and I think it means there should be 8 by 8 blocks of stream to start encipher. What should I do?

Encipher method of Blowfish:

public void Encipher(byte[] data, int length)
{
    uint xl, xr;
    if ((length % 8) != 0) <-- Exception Line
        throw new Exception("Invalid Length");
    for (int i = 0; i < length; i += 8)
    {
        // Encode the data in 8 byte blocks.
        xl = (uint)((data[i] << 24) | (data[i + 1] << 16) | (data[i + 2] << 8) | data[i + 3]);
        xr = (uint)((data[i + 4] << 24) | (data[i + 5] << 16) | (data[i + 6] << 8) | data[i + 7]);
        Encipher(ref xl, ref xr);
        // Now Replace the data.
        data[i] = (byte)(xl >> 24);
        data[i + 1] = (byte)(xl >> 16);
        data[i + 2] = (byte)(xl >> 8);
        data[i + 3] = (byte)(xl);
        data[i + 4] = (byte)(xr >> 24);
        data[i + 5] = (byte)(xr >> 16);
        data[i + 6] = (byte)(xr >> 8);
        data[i + 7] = (byte)(xr);
    }
}

My encryption method:

private void EncryptFile(string szFilePath, string szInfoFile, string szKey, string szEncryptedFile = "")
        {
            // Blowfish
            Blowfish alg = new Blowfish(Encoding.Unicode.GetBytes(szKey));

            // Open file
            System.IO.FileStream originalStream = System.IO.File.OpenRead(szFilePath);

            // Store original file length
            long originalLength = originalStream.Length;
            System.IO.File.WriteAllText(szInfoFile, originalLength.ToString());

            Byte[] buffer = new byte[originalStream.Length + (originalStream.Length % 8)];
            originalStream.Read(buffer, 0, buffer.Length);
            originalStream.Close();

            // Encrypt
            alg.Encipher(buffer, buffer.Length);

            string szEncFile;

            if (szEncryptedFile != string.Empty) szEncFile = szEncryptedFile; else szEncFile = szFilePath;

            System.IO.FileStream stream = new System.IO.FileStream(szEncFile, System.IO.FileMode.Create);
            stream.Write(buffer, 0, buffer.Length);
            stream.Close(); 
        }

Thanks.


Solution

  • If what you're trying to do is round a value up to the next value divisible by 8, then you should do this instead:

    Byte[] buffer = new byte[originalStream.Length + (8-(originalStream.Length % 8))];