Bad Length Error in Rsa 加密解密

Bad Length Error in Rsa encryption decryption

请帮我找出以下 RSA 加密代码中的问题

public static void Test()
{
    CspParameters cspParams = new CspParameters { ProviderType = 1 };
    RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(1024, cspParams);

    var PublicKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(false));  //I have to save it as string in some json/app.config configuration file
    var PrivateKey = Convert.ToBase64String(rsaProvider.ExportCspBlob(true));  //I have to save it as string in some json/app.config configuration file
    
    var encrypt = EncryptText(PublicKey,  Encoding.UTF8.GetBytes(FromSomeFile()));
    
    var decrypt = DecryptData(PrivateKey, encrypt);
}

static byte[] EncryptText(string publicKey, byte[] dataToEncrypt)
{   
    byte[] encryptedData;
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {                
        rsa.ImportCspBlob(Convert.FromBase64String(publicKey));             
        encryptedData = rsa.Encrypt(dataToEncrypt, false);
    }
    return encryptedData;
}

// Method to decrypt the data withing a specific file using a RSA algorithm private key   
static string DecryptData(string privateKey, byte[] dataToDecrypt)
{
    
    // Create an array to store the decrypted data in it   
    byte[] decryptedData;
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.ImportCspBlob(Convert.FromBase64String(privateKey));              
        decryptedData = rsa.Decrypt(dataToDecrypt, false);
    }           
    
    return Encoding.UTF8.GetString(decryptedData, 0, decryptedData.Length); ;
}

RSA只能用于加密长度小于模数的消息。小多少取决于填充,例如在 PKCS#1 v1.5, s 的情况下为 11 个字节。 here. In the case of OAEP, the number of bytes claimed by padding depends on the digest used, s. here. The details are described in RFC8017, RSAES-PKCS1-v1_5 and RSAES-OAEP
为了完整起见:没有填充的 RSA(教科书 RSA)允许对消息进行加密,直到正好达到模数的长度。但在实践中,出于安全原因必须始终使用填充,因此教科书 RSA 不是真正的选择。

发布的代码使用 1024 位的 RSA 密钥和 PKCS#1 v1.5 填充。因此,要加密的消息的最大大小为 117 字节。较大的消息会引发 CryptographicException(错误长度)。这就是您遇到问题的原因。

8192 位(1024 字节)的密钥理论上 允许使用 PKCS#1 v1.5 填充加密最长 1013 字节的消息。但是,性能会随着密钥大小 s 的增加而急剧下降。 here.

Symmetric encryption is more performant than asymmetric encryption. Therefore, in practice larger data volumes are encrypted using symmetric encryption, e.g. AES. However, symmetric encryption has the problem that the communication partners have to exchange the symmetric key. Asymmetric encryption, e.g. RSA, is typically used for this purpose (hybrid encryption), since only the public keys are needed for encryption (which can therefore be exchanged over an insecure channel). However, to prevent a deceptive replacement of the public keys (man in the middel attack), a complex public key infrastructure一般是必须的。