Search code examples
c#.netcryptographyrijndael

Encryption/Decryption not Returning Original Length of Data


I don't understand why the code below is failing.

public string Encrypt(System.Byte value)
{
    return Convert.ToBase64String(Encrypt(BitConverter.GetBytes(value)));
}

public bool Decrypt(string encryptedValue, out System.Byte value)
{
    byte[] data = Decrypt(Convert.FromBase64String(encryptedValue));
    if (data.Length != sizeof(System.Byte))  // <===== THIS IS TRUE!!!
    {
        value = default(System.Byte);
        return false;
    }
    value = data[0];
    return true;
}

Specifically, the byte array returned from Decrypt(byte[], out byte) is 2 bytes long, instead of the expected 1 byte in length.

Note that the second byte appears to always be zero and the first byte has the correct value. So I can make the code work by just taking the first byte. But does anyone know why I'm getting the extra byte. I'm guessing it may be related to Convert.FromBase64String.

Below are my underlying Encrypt and Decrypt methods.

public virtual byte[] Encrypt(byte[] data)
{
    using (Rijndael algorithm = Rijndael.Create())
    using (ICryptoTransform encryptor = algorithm.CreateEncryptor(Key.KeyString, Key.KeyBytes))
    {
        MemoryStream ms = new MemoryStream();
        using (Stream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
        {
            cs.Write(data, 0, data.Length);
        }
        return ms.ToArray();
    }
}

public virtual byte[] Decrypt(byte[] data)
{
    using (Rijndael algorithm = Rijndael.Create())
    using (ICryptoTransform decryptor = algorithm.CreateDecryptor(Key.KeyString, Key.KeyBytes))
    {
        MemoryStream ms = new MemoryStream();
        using (Stream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
        {
            cs.Write(data, 0, data.Length);
        }
        return ms.ToArray();
    }
}

Solution

  • The BitConverter.GetBytes method doesn't provide an overload that takes a byte. My guess is that it's promoting it to a (2 byte) ushort and then encrypting that, hence the 2 byte result when you decrypt.