input too large for RSA cipher with BouncyCastle

2020-07-29 23:42发布

I'm trying to write a service to SFTP to a server on a given interval, download all files in a directory, and then decrypt them for processing.

The decrypt method was working at one point, and I have no modified it since. I am still using the same keys as when it did successfully work.

I am using the PGPEncrypt, PGPDecrypt, and PGPEncryptionKeys classes for BouncyCastle found here: https://github.com/sledwith/PGP-Decryption-With-C-Sharp

Additionally, I have modified the code as shown here: Exception on decrypting file using BouncyCastle PGP

If you noticed, I commented on how that fixed my code and the decryption worked.

Now, it isn't.

Does anyone have some insight why this might have happened, or how I could go about fixing it?

3条回答
手持菜刀,她持情操
2楼-- · 2020-07-29 23:52

I am going to make a guess that you are using a 1024 bit RSA public/private key and trying to encrypt 128 bytes of something with it? If I am right, use a larger RSA key (RSA 4096 will allow you to encrypt up to ~500 bytes).

I note in the linked post you say this is sporadic. Some googling indicates that if you have leading zeros in the to-be-encrypted bytes it may be able to handle a full 128 bytes.

Also - if you are just encrypting "data" with the keypair, you need to be certain it will not overrun these limitations (240 or so bytes for RSA 2048 and 500 or so for RSA 4096 accounting for padding). Good practice and future proofing would be to implement a symmetric key encryption of all your data and just use the RSA key to encrypt / decrypt your keys.

查看更多
孤傲高冷的网名
3楼-- · 2020-07-29 23:57

I think I resolved this problem; please try this code.

public string StringToDecrypt(string text)
{
    byte[] toDecrypt = Convert.FromBase64String(text);
    AsymmetricCipherKeyPair keyPair;

    using (var reader = File.OpenText(@"Private Key File Path"))
    {
        keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();   
    }

    var engine = new RsaEngine();
    engine.Init(false, keyPair.Private);

    return Encoding.UTF8.GetString(engine.ProcessBlock(toDecrypt, 0, toDecrypt.Length));
}
查看更多
做个烂人
4楼-- · 2020-07-30 00:11

If you're not dead-set on using the PGP process explicitly, you might use my library here:

https://github.com/zenith-nz/ObscurCore

Its "banner feature" is not yet fully active (creating encrypted archives of a kind), but it does everything that you want it for, it appears - it does key derivation with a ECDHC scheme, UM1, and implements a large variety of block and stream ciphers. It's built on top of BouncyCastle.

查看更多
登录 后发表回答