简体   繁体   中英

Successfully RSA Encrypting data in C#

I am trying to implement RSA Encryption into my C# program.

Here is my code :

using System;
using System.Security.Cryptography;

string dataToEncrypt = "Data to Encrypt here";
string modulus= "Public Key here";
string exponent= "Public Key Kxpiry here";

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

RSAParameters RSAKeyInfo = new RSAParameters();

RSAKeyInfo.Modulus = Encoding.UTF8.GetBytes(modulus);
RSAKeyInfo.D = Encoding.UTF8.GetBytes(dataToEncrypt);
RSAKeyInfo.Exponent = Encoding.UTF8.GetBytes(exponent);

RSA.ImportParameters(RSAKeyInfo);

I receive this error code :

System.Security.Cryptography.CryptographicException: 'Bad Data.'

This line is giving the error : RSA.ImportParameters(RSAKeyInfo);

Other information :

  • Visual Studio 2019
  • Windows Forms App (.NET Framework)
  • Operating System : Windows 10 Professional

What am I missing/doing wrong?

RSA key generation is a very specific process, which relies or two (or more) prime numbers. You cannot just pick random values for RSA to be secure. Then again, RSA relies on modular exponentiation during encryption, and that may still "work", ie generate an insecure answer.

CSP (cryptographic service providers) may however pose additional restrictions. For instance, the Microsoft CSP has the following restriction regarding key size:

Windows CSPs enable key sizes of 384 to 16384 bits for Windows versions prior to Windows 8.1, and key sizes of 512 to 16384 bits for Windows 8.1.

As the key size is specified to be the size of the modulus. Furthermore, the key size must be a multiple of 8 as well. This means that the most significant bit in the byte array must be set to 1, and this is never the case for UTF-8.

Furthermore there may be restrictions on the public exponent as well; for the Windows CSP it needs to be smaller than 32 bits. Generally it is simply set to the value 010001 hex (65537 or the fifth prime of Fermat, called F4).


The CNG implentation of RSA seems more flexible, so you may try that as well if you want to test some specifics of RSA.

However, in the end you need to use the RSA key pair generation procedures to create a valid RSA key pair; nothing else will be secure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM