Click here to Skip to main content
15,878,871 members
Articles / Programming Languages / C#
Article

Public Key RSA Encryption in C# .NET

Rate me:
Please Sign up or sign in to vote.
4.74/5 (108 votes)
29 Jan 20078 min read 1M   42.7K   244   137
1024/2048 bit RSA cryptography in a "Notepad style" program.

Image 1

General Information

RSACryptoPad is a very basic display of the RSA encryption abilities in the .NET framework libraries. This code will use public key RSA encryption presented in a notepad-style program. You know…spy stuff. :-)

Your best resource for RSA encryption is RSA Security.

The way you use this code is to change it to suit your purposes and/or take pieces of it to use in your own program. There are encryption projects on CodeProject already but I am sure you'll see the difference in what I am doing.

I realize to be productive you may want to skip the details of this program and utilize only the main encryption functions. So, here is a quick listing of them:

public string EncryptString( string inputString, int dwKeySize, 
                             string xmlString )
{
    // TODO: Add Proper Exception Handlers
    RSACryptoServiceProvider rsaCryptoServiceProvider = 
                                  new RSACryptoServiceProvider( dwKeySize );
    rsaCryptoServiceProvider.FromXmlString( xmlString );
    int keySize = dwKeySize / 8;
    byte[] bytes = Encoding.UTF32.GetBytes( inputString );
    // The hash function in use by the .NET RSACryptoServiceProvider here 
    // is SHA1
    // int maxLength = ( keySize ) - 2 - 
    //              ( 2 * SHA1.Create().ComputeHash( rawBytes ).Length );
    int maxLength = keySize - 42;
    int dataLength = bytes.Length;
    int iterations = dataLength / maxLength;
    StringBuilder stringBuilder = new StringBuilder();
    for( int i = 0; i <= iterations; i++ )
    {
        byte[] tempBytes = new byte[ 
                ( dataLength - maxLength * i > maxLength ) ? maxLength : 
                                              dataLength - maxLength * i ];
        Buffer.BlockCopy( bytes, maxLength * i, tempBytes, 0, 
                          tempBytes.Length );
        byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt( tempBytes,
                                                                  true );
        // Be aware the RSACryptoServiceProvider reverses the order of 
        // encrypted bytes. It does this after encryption and before 
        // decryption. If you do not require compatibility with Microsoft 
        // Cryptographic API (CAPI) and/or other vendors. Comment out the 
        // next line and the corresponding one in the DecryptString function.
        Array.Reverse( encryptedBytes );
        // Why convert to base 64?
        // Because it is the largest power-of-two base printable using only 
        // ASCII characters
        stringBuilder.Append( Convert.ToBase64String( encryptedBytes ) );
    }
    return stringBuilder.ToString();
}

public string DecryptString( string inputString, int dwKeySize, 
                             string xmlString )
{
    // TODO: Add Proper Exception Handlers
    RSACryptoServiceProvider rsaCryptoServiceProvider
                             = new RSACryptoServiceProvider( dwKeySize );
    rsaCryptoServiceProvider.FromXmlString( xmlString );
    int base64BlockSize = ( ( dwKeySize / 8 ) % 3 != 0 ) ?
      ( ( ( dwKeySize / 8 ) / 3 ) * 4 ) + 4 : ( ( dwKeySize / 8 ) / 3 ) * 4;
    int iterations = inputString.Length / base64BlockSize; 
    ArrayList arrayList = new ArrayList();
    for( int i = 0; i < iterations; i++ )
    {
        byte[] encryptedBytes = Convert.FromBase64String( 
             inputString.Substring( base64BlockSize * i, base64BlockSize ) );
        // Be aware the RSACryptoServiceProvider reverses the order of 
        // encrypted bytes after encryption and before decryption.
        // If you do not require compatibility with Microsoft Cryptographic 
        // API (CAPI) and/or other vendors.
        // Comment out the next line and the corresponding one in the 
        // EncryptString function.
        Array.Reverse( encryptedBytes );
        arrayList.AddRange( rsaCryptoServiceProvider.Decrypt( 
                            encryptedBytes, true ) );
    }
    return Encoding.UTF32.GetString( arrayList.ToArray( 
                              Type.GetType( "System.Byte" ) ) as byte[] );
}

The following tutorial is provided if you feel you want to know a little more about RSA cryptography.

RSA Cryptography Tutorial

The security of a cryptographic system should not be based on the privacy of its implementation. It should be based on the strength of its underlying mathematical cryptographic algorithm. An algorithm is a procedure or formula. The challenge of any cryptographic algorithm is to stand the test of time once the “collective masses” know everything about its implementation.

RSA cryptography is named after its inventors Ron Rivest, Adi Shamir, and Len Adleman. However, the idea was first discovered in 1973 by a member of the British government named Clifford Cocks.

A few months prior to the writing of this article a successful factorization of a 193-digit prime number which in this case was a RSA 640-bit encryption key has been factored successfully by a research team comprised of F. Bahr, M. Boehm, J. Franke, and T. Kleinjung. The effort took approximately 30 2.2GHz-Opteron-CPU years which is over five months of calendar time according to the submitters.

In order to understand that last statement it is necessary to know that factorization is the resolution of an integer into “factors” and that cryptographic keys are very large numbers measured in “bits” which represent the binary digits it takes to compose the number. This is significant because it means that 640-bit and lower RSA encryption keys are no longer completely secure.

The mention of the word “cryptography” elicits many varying reactions. Some of the reactions you may receive are: boredom, confusion, concern, and maybe even fear. The reason for this emotional reaction is based on the relative significance to the individual.

In cryptography, everything starts with data that can be read without any extra effort referred to as "plain-text". The method of converting plain-text into unreadable gibberish called “cipher-text” is encryption. The process of reverting this gibberish back into the original plain-text is called decryption. Simply stated, cryptography is the science of using mathematics to scramble and descramble information. Cryptography allows the storage and transmission of sensitive material so that it can only be read by the intended recipient.

How cryptography works is by the use of cryptographic algorithms called “ciphers” and “deciphers”, which are mathematical functions that work with cryptographic keys to encrypt and decrypt plain-text. The bigger the key, the more secure the cipher-text. The same plain-text encrypts to different cipher-text with different keys.

Public key cryptography utilizes a public key for encryption as well as a corresponding private key for decryption. Because it uses two differing keys, it is sometimes called asymmetric cryptography. Asymmetric means unbalanced or different. While the public and private keys are mathematically related, it is computationally infeasible to deduce the private key from the public key, which requires factoring large prime numbers, without massive amounts of computing power. The primary advantage of public key cryptography is that it allows people who have no preexisting arrangement with you to exchange data securely. You publish your public key to the world while keeping your private key secret. Anyone with a copy of your public key can then encrypt information that only you can decrypt with your private key.

Base-64 Numbers

Throughout cryptography, you will see often see numbers represented as large character strings. For example, a RSA Modulus, which is a part of a RSA public key, may appear as follows:

6nfX01TUfFaliu1wit5RJ5JQNFBzxWSePsviImlPKReIFSjpktWW6RbGk4pNj+fqh2DOWquaMzdXI27YFVuFJQ==

Do not let the cryptic stuff discourage you. This string of characters is really just a very large number represented in a way with which you may not be familiar. This number has been converted to a base-64 number. To understand base-64 encoded numbers, begin by recalling elementary school math. When we first learned about numbers, we were taught that, in the decimal system (base-10), things are organized into columns:

Hundreds|Tens|Ones
1 9 3

Therefore, the number "193" is 1-hundreds plus 9-tens plus 3-ones. Years later, we learned that the ones column meant 100, the tens column meant 101, the hundreds column 102 and so on, so the number 193 is really:

{ ( 1 * 10<sup>2 </sup>) + ( 9 * 10<sup>1 </sup>) + ( 3 * 10<sup>0 </sup>) }

The base-64 numbering system works under the exact same principles as the decimal system, only it operates in base-64 rather than base-10. In other words, instead of columns being:

10<sup>2</sup>|10<sup>1</sup>|10<sup>0</sup>

They are:

64<sup>2</sup>|64<sup>1</sup>|64<sup>0</sup>

Since there are not enough numbers to properly represent the numbers we are creating, letters are used as well. Here is a quick break down of what the letters represent:

0-25 is 'A'-'Z'
26-51 is 'a'-'z'
52-61 is '0'-'9'
62 is '+'
63 is '/'
Pad is '='

In order to understand public key cryptography it is necessary to understand what composes the encryption components. I do not implement the following processes in my program as they are already provided in the .NET framework. However, I felt a description of the process was necessary. An RSA private key may have two representations. However, only the one demonstrated in this article's corresponding programming project RSACryptoPad that uses the Chinese remainder theorem1 is explained here. In order to generate better understanding I have used plain English rather than modular arithmetic formulas wherever possible.

Skipping a lot of detail, here is the procedure for creating the RSA components:

  1. Generate two different large odd prime numbers, called P and Q, of about the same size where P is greater than Q that when multiplied together give a product that can be represented by the required bit length you have chosen, e.g. 1024 bits. These numbers are used to create your Modulus.
  2. Choose an Exponent that is greater than three, and less than Modulus - 1. Exponent does not have to be prime, but it has to be odd. ( P – 1 ) * ( Q – 1 ) can't be prime because it's an even number. Then ensure that the greatest common denominator of Exponent and the least common multiple of P – 1 and Q – 1 equal 1.
  3. To create D the private exponent simply find an integer X which causes D = ( X * ( ( P – 1 ) * ( Q – 1 ) ) + 1 ) / E to be an integer, then use that value for D.
  4. The following key components DP, DQ, and InverseQ are found with the following formulas2 (all components are positive integers where P>Q):
    • DP = ( 1 / Exponent) mod ( P - 1 )
    • DQ = (1 / Exponent ) mod ( Q - 1 )
    • InverseQ = ( 1 / Q ) mod P where P > Q

When representing the plain-text to plain-text octets in order to secure the message more thoroughly it is usual to add padding characters to make it less susceptible to certain types of attack. I leave this one for your further research. After all that has been accomplished you have public and private keys ready for encryption which are then stored as base-64 numbers.

The following is a very generalized explanation of the encryption and decryption functions, the cipher is the encryption function and the decipher is the decryption function2.

The encryption function is:

C = ( TExponent ) mod Modulus, where C is the cipher-text (a positive integer), and T is the plain-text (a positive integer). T the plain-text being encrypted must be less than the Modulus.

The decryption function is:

The decryption function is T = (CD) mod Modulus, where C is the cipher-text (a positive integer), T is the plain-text (a positive integer). D is the secret exponent.

You can publish your public key to the world freely, because there are no known quick methods of calculating your D, P, and Q.

In conclusion, I included a program written C# using the .NET Framework libraries which implement RSA cryptography.

History

The Microsoft Cryptographic Service Provider Programmer's Guide was used as my reference material and it is written in C#. This little program was originally written in Visual Studio 2003 with .NET Framework v1.1 which may still function. However, I was using Microsoft Visual C# 2005 Express Edition to update this code. So, I only know only of its ability to function with .NET v2.0. This program requires Windows XP/Server 2003. The following enhancements have been made since the last version:

  • Removed some functionality invalid in .NET 2.0
  • Enhanced the encryption functions to handle any valid .NET key length
  • Added code to save form settings
  • Added drag and drop functionality

1 For a thorough explanation of the Chinese remainder theorem, please refer to [RSA02].

2 For a thorough explanation of modular arithmetic, please refer to [RSA02].

References

  • [COX73] Clifford Cocks. A note on 'Non-Secret Encryption', CESG research report, 20th November 1973.
  • [RSA04] RSA Laboratories. RSA Security - The RSA Challenge Numbers, 2004.
  • [PGP04] PGP Corporation, An introduction to cryptography. PGP Corporation, 2004.
  • [MSC96] Microsoft Corporation, Microsoft Cryptographic Service Provider Programmer's Guide, Microsoft Corporation, 1996.
  • [RSA02] RSA Laboratories. PKCS #1 v2.1: RSA Encryption Standard, 2002.
  • [RSA78] R. Rivest, A. Shamir, and L. Adleman. A method for obtaining digital signatures and public-key cryptosystems. Communications of the ACM, 21 (2), pp. 120-126, 1978.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
Mathew John Schlabaugh

Comments and Discussions

 
GeneralMy vote of 5 Pin
amardhere3-Aug-22 12:32
amardhere3-Aug-22 12:32 
QuestionLicense for this code Pin
skybluecodeflier6-Apr-16 5:28
skybluecodeflier6-Apr-16 5:28 
SuggestionUsing a Real Key Files (pfx,cer) Pin
Boss_mex9-Oct-15 5:13
Boss_mex9-Oct-15 5:13 
QuestionPublic Key RSA Encryption in C# .NET Pin
Member 117354372-Jun-15 1:12
Member 117354372-Jun-15 1:12 
Hello, I need help about your project "Public Key RSA Encryption in C# .NET".
Your program is work and I like it. Nice job.
I am student and I am new in this world of programming.
I love networks more than programming but now I have to do something different.
Your code is shared on network with source code and I am happy to see it.
Can you help me? How can I change it to work for me. I need to edit your help menu for my examination and maybe translate to my country language.
I need information about your autobiography also because in my work I will use your experience and project.
I will be happy to receive feedback from you and coordinates to move in social networks or email adress .
You are a valuable source ! I have you nice day. And thank you. Smile | :)
GeneralMy vote of 5 Pin
Alberto M.16-Jul-14 8:34
Alberto M.16-Jul-14 8:34 
QuestionNeed to check dwKeySize? Pin
Win32nipuh4-Feb-14 22:46
professionalWin32nipuh4-Feb-14 22:46 
Generalthanks a lot! Pin
korvarn korvarn8-Oct-13 3:21
korvarn korvarn8-Oct-13 3:21 
QuestionError in Decryption Pin
Ajendra Yadav4-Oct-13 20:41
Ajendra Yadav4-Oct-13 20:41 
QuestionWell explained Pin
Nermin Huskic3-Aug-13 12:04
Nermin Huskic3-Aug-13 12:04 
QuestionEncryption using private key / Decryption using public key fails Pin
Marco Giacinti14-May-13 1:47
Marco Giacinti14-May-13 1:47 
GeneralMy vote of 5 Pin
AmitGajjar17-Apr-13 0:08
professionalAmitGajjar17-Apr-13 0:08 
Generalnice rsa working example Pin
Brent Huot14-Feb-13 5:57
Brent Huot14-Feb-13 5:57 
GeneralMy vote of 5 Pin
CafedeJamaica26-Oct-12 9:27
professionalCafedeJamaica26-Oct-12 9:27 
QuestionCan i use my private key to encrypt the data and public key to decrypt the cipher text. Pin
pritam hinger16-Oct-12 21:29
pritam hinger16-Oct-12 21:29 
AnswerRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pin
Dylan Roy25-Oct-12 5:24
professionalDylan Roy25-Oct-12 5:24 
GeneralRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pin
Joshua3222-Nov-12 9:12
Joshua3222-Nov-12 9:12 
GeneralRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pin
vbscript223-Jan-13 7:34
vbscript223-Jan-13 7:34 
GeneralRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pin
Dylan Roy27-Mar-13 4:07
professionalDylan Roy27-Mar-13 4:07 
GeneralMy vote of 5 Pin
Atiq Rehman12-Jul-12 0:24
Atiq Rehman12-Jul-12 0:24 
QuestionFaster way of finding D Pin
reo6329-Jun-12 10:41
reo6329-Jun-12 10:41 
Questionprivate & public key problem Pin
Cool Smith12-Feb-12 8:24
Cool Smith12-Feb-12 8:24 
AnswerRe: private & public key problem Pin
Member 866458613-Jul-12 3:04
Member 866458613-Jul-12 3:04 
QuestionError While Encrypting A File Pin
hassan faghihi7-Jan-12 1:49
professionalhassan faghihi7-Jan-12 1:49 
GeneralMy vote of 5 Pin
camagames20-Dec-11 4:41
camagames20-Dec-11 4:41 
QuestionHelp with reading Microsoft PKI data base. Pin
msedu29-Nov-11 11:08
msedu29-Nov-11 11:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.