Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Public Key RSA Encryption in C# .NET

0.00/5 (No votes)
29 Jan 2007 12  
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. :-)

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 * 102 ) + ( 9 * 101 ) + ( 3 * 100 ) }

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:

102|101|100

They are:

642|641|640

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