Org.BouncyCastle.Crypto.DataLengthException: last block incomplete in decryption

455 Views Asked by At

I have implemented AES 256 ECB Encryption and Decryption using Bouncy Castle library. I am able to encrypt the data , but unable to decrypt the cipher text. It throws an error saying "Org.BouncyCastle.Crypto.DataLengthException: last block incomplete in decryption". Following is my code for Encryption and Decryption;

public byte[] encrypt(byte[] skey, byte[] data)
{
   PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
   new AesEngine(), new Pkcs7Padding());
   cipher.Init(true, new KeyParameter(skey));
   int outputSize = cipher.GetOutputSize(data.Length);
   byte[] tempOP = new byte[outputSize];
   int processLen = cipher.ProcessBytes(data, 0, data.Length, tempOP, 0);
   int outputLen = cipher.DoFinal(tempOP, processLen);
   byte[] result = new byte[processLen + outputLen];
   Array.Copy(tempOP, 0, result, 0, result.Length);
   return result;
}
public byte[] decrypt(byte[] skey, byte[] data)
{
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(
    new AesEngine(), new Pkcs7Padding());
    cipher.Init(false, new KeyParameter(skey));
    int outputSize = cipher.GetOutputSize(data.Length);

    byte[] tempOP = new byte[outputSize];
    int processLen = cipher.ProcessBytes(data, 0, data.Length, tempOP, 0);
    int outputLen = cipher.DoFinal(tempOP, processLen);

    byte[] result = new byte[processLen + outputLen];
    Array.Copy(tempOP, 0, result, 0, result.Length);
    return result;    
}
1

There are 1 best solutions below

1
山田雄基 On

I have same issue.

Type : Org.BouncyCastle.Crypto.DataLengthException StackTrace : at Org.BouncyCastle.Crypto.Paddings.PaddedBufferedBlockCipher.DoFinal(Byte[] output, Int32 outOff) in /_/crypto/src/crypto/paddings/PaddedBufferedBlockCipher.cs:line 281

-- FoFinal method

        if (bufOff == blockSize)
        {
            num = cipher.ProcessBlock(buf, 0, buf, 0);
            bufOff = 0;
            try
            {
                num -= padding.PadCount(buf);
                Array.Copy(buf, 0, output, outOff, num);
                return num;
            }
            finally
            {
                Reset();
            }
        }

        Reset();
        **throw new DataLengthException("last block incomplete in decryption");**