'RSAEngine Index was outside the bounds of the array

I need to encrypt the AES key with public RSA key, but I do have a problem on return engine.ProcessBlock. It keeps giving me the error 'Index was outside the bounds of the array' and the blocksize is only 245 bytes long. 'Source array was not long enough. Check srcIndex and length, and the array's lower bounds.'

    public void Main()
    {
        var pem = @"C:\Temp\test\publickey.pem";

        AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
        AES.Padding = PaddingMode.PKCS7;
        AES.Mode = CipherMode.CBC;
        AES.BlockSize = 128;
        AES.KeySize = 256;
      
        AES.GenerateKey();
        AES.GenerateIV();

        byte[] key = AES.Key;
        byte[] iv = AES.IV;

        encryptAES(AES, file, key, iv);
        decryptAES(AES, file + ".encrypted", key, iv);

        byte[] encryptedAes = Encrypt(key, ReadAsymmetricKeyParameter(pem));
    }

    public byte[] Encrypt(byte[] data, AsymmetricKeyParameter key)
    {
        var engine = new Pkcs1Encoding(new RsaEngine());
        engine.Init(true, key);
        var blockSize = engine.GetInputBlockSize();
        byte[] enc = engine.ProcessBlock(data, 0, blockSize);
        return enc;
    }

    public AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
    {
        var fileStream = File.OpenText(pemFilename);
        var pemReader = new PemReader(fileStream);
        var KeyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();
        return KeyParameter;
    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source