使用块的RSA加密的加密数据大小是多少

What is the encrypted data size for RSA encryption using blocks

我有使用 BouncyCastle 库进行 RSA 加密的 c# 代码:

public string EncryptData(string publicKey, string data)
{
    try
    {
        var bytesToEncrypt = Encoding.UTF8.GetBytes(data);
        int srclen = bytesToEncrypt.Length;

        //Prepare encryption engine
        var encryptEngine = new Pkcs1Encoding(new RsaEngine());

        //Initialize Key
        using (var txtreader = new StringReader(publicKey))
        {
            var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
            encryptEngine.Init(true, keyParameter);
        }

        //Encrypt in loop
        byte[] complete = new byte[0];
        int src_block_size = encryptEngine.GetInputBlockSize();
        for (int idx = 0; idx < srclen; idx += src_block_size)
        {
            int data_len = srclen - idx;
            if (data_len > src_block_size)
            {
                data_len = src_block_size;
            }

            var encryptedChunk = encryptEngine.ProcessBlock(bytesToEncrypt, idx, data_len);
            complete = CombineByteArrays(complete, encryptedChunk);
        }

        var finalString = Convert.ToBase64String(complete);
        return finalString;
    }
    catch (InvalidCipherTextException)
    {

    }
}

如您所见,它将数据分块并加密每个块。当我加密数据时,我可以看到 finalstring 是一个可变大小(请注意 finalString 基本上是加密字节的 base64 编码)。不确定决定长度的因素是什么,它是我可以依赖的固定模式还是不确定的。我需要确保 finalString 在限制范围内(字符数)。

加密的 RSA 块的大小由密钥大小决定。 RSA 块中可以加密的数据量同时也取决于 RSA 密钥的大小减去填充占用的数据。

通常 RSA 不应该用于批量加密,因为它很慢(可能是 1000 倍)并且由于填充(你应该采用)。如果您确实需要 RSA 中的两个密钥的好处,您应该使用 hybrid encryption 方法。如果您实际上不需要这两个密钥,那么您需要使用像 AES 这样的对称密码。此外,当使用对称加密时,您将获得开箱即用的阻止支持,这与您使用 RSA.

所拥有的相反。