Click here to Skip to main content
Click here to Skip to main content

Public Key RSA Encryption in C# .NET

, 29 Jan 2007
Rate this:
Please Sign up or sign in to vote.
1024/2048 bit RSA cryptography in a "Notepad style" program.

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. Smile | :)

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 c***s.

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 c***s. 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

Share

About the Author

Mathew John Schlabaugh
Web Developer
United States United States
Mathew John Schlabaugh

Comments and Discussions

 
GeneralMy vote of 5 PinmemberAlberto Molero16-Jul-14 8:34 
QuestionNeed to check dwKeySize? PinmemberWin32nipuh4-Feb-14 22:46 
Generalthanks a lot! Pinmemberkorvarn korvarn8-Oct-13 3:21 
QuestionError in Decryption PinmemberAjendra Yadav4-Oct-13 20:41 
QuestionWell explained PinmemberNerminHuskic3-Aug-13 12:04 
QuestionEncryption using private key / Decryption using public key fails PinmemberMarco Giacinti14-May-13 1:47 
GeneralMy vote of 5 Pinprofessional@AmitGajjar17-Apr-13 0:08 
Generalnice rsa working example PinmemberBrent Huot14-Feb-13 5:57 
GeneralMy vote of 5 PinmemberMathlab26-Oct-12 9:27 
QuestionCan i use my private key to encrypt the data and public key to decrypt the cipher text. Pinmemberpritam hinger16-Oct-12 21:29 
AnswerRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pinmemberdkroy25-Oct-12 5:24 
GeneralRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. PinmemberJoshua3222-Nov-12 9:12 
GeneralRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pinmembervbscript223-Jan-13 7:34 
GeneralRe: Can i use my private key to encrypt the data and public key to decrypt the cipher text. Pinmemberdkroy27-Mar-13 4:07 
GeneralMy vote of 5 PinmemberAtiq11412-Jul-12 0:24 
QuestionFaster way of finding D Pinmemberreo6329-Jun-12 10:41 
Questionprivate & public key problem PinmemberCool Smith12-Feb-12 8:24 
AnswerRe: private & public key problem PinmemberMember 866458613-Jul-12 3:04 
QuestionError While Encrypting A File Pinmemberhassan faghihi7-Jan-12 1:49 
GeneralMy vote of 5 Pinmembercamagames20-Dec-11 4:41 
QuestionHelp with reading Microsoft PKI data base. Pinmembermsedu29-Nov-11 11:08 
GeneralMy vote of 1 Pinmemberbilal@programmer.im24-Nov-11 23:59 
QuestionCode needs explanations PinmemberSupratik sadhuka28-Aug-11 19:43 
GeneralI translated the code from C # to VB, it seems to work. PinmemberAngelo Ciavarella15-Feb-11 22:53 
GeneralRe: I translated the code from C # to VB, it seems to work. PinmemberMathew John Schlabaugh16-Feb-11 6:41 
GeneralClarification required on permission to use the software PinmemberPaul/Singapore7-Dec-10 11:34 
GeneralI need an help, understanding somethings PinmemberOngcos12-Oct-10 6:45 
QuestionHow can I include Digital Signature and Digital Signature Verification in the same project ? PinmemberTejas_Warudkar13-Jan-10 2:04 
GeneralDH Key exchange... Pinmemberalam54b26-Dec-09 3:11 
Generalthanks Pinmembertnla9-Nov-09 7:46 
Questiondifference between encryption and signing? PinmemberMember 151309928-Oct-09 2:40 
Generalthanks Pinmember ThatsAlok 21-Jul-09 18:43 
GeneralError occured while decoding oaep padding PinmemberMeetu Choudhary5-Jun-09 1:24 
QuestionSetting the default key Pinmemberpapa.coen27-Jan-09 3:54 
AnswerRe: Setting the default key Pinmemberreaplo4-Mar-09 5:21 
AnswerRe: Setting the default key PinmemberGluups27-Jun-10 2:58 
QuestionHow to generate 2048 bits keys with exponent 0x10001 ? [modified] Pinmemberv_srinu_26_f17-Dec-08 10:40 
GeneralTry Large File PinmemberOMSSD8414-Sep-08 21:41 
GeneralRe: Try Large File Pinmemberpsikotic1-Dec-08 6:18 
GeneralRe: Try Large File PinmemberOMSSD841-Dec-08 12:33 
GeneralRe: Try Large File Pinmemberpsikotic2-Dec-08 4:56 
GeneralRe: Try Large File Pinmemberhassan faghihi6-Jan-12 6:40 
QuestionHow can i assign my own public key to rsacryptoserviceprovider PinmemberMember 401190326-Jul-08 18:19 
GeneralSecurity questions PinmemberCuchuk Sergey10-Jul-08 2:59 
Questioni cant convert this program into vb.net Pinmemberjeipiyaku3-Jul-08 19:03 
AnswerRe: i cant convert this program into vb.net Pinmemberjohankrantz6-Jul-08 22:20 
AnswerRe: i cant convert this program into vb.net Pinmemberjeipiyaku7-Jul-08 2:35 
QuestionWeird math when converting to vb.net Pinmemberjohankrantz4-Jun-08 6:37 
GeneralRe: Weird math when converting to vb.net Pinmemberjeipiyaku6-Jul-08 4:21 
AnswerRe: Weird math when converting to vb.net PinmemberCaptain Toad10-Jul-08 6:42 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140827.1 | Last Updated 30 Jan 2007
Article Copyright 2005 by Mathew John Schlabaugh
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid