Return to HomePage




Import an RSA Public Key from a file and Encrypt a Message (VB.NET)


Applies to

* .NET Framework 2.0
* VB.NET

Summary

The purpose of this code snippet is to illustrate how the recipient of an XML file containing containing an RSA public key can read the file and encrypt a message for the sender using this key.


Objectives

* Securely generate a message from an RSA key that only the owner of the key can decrypt and read.


Scenarios

* Distributed client-server architecture where clients need to send confidential encrypted messages to the server but don't need to ever read those messages
* Application does not want to maintain a dedicated key store for encryption purposes


Solution Example

Function ReadRSAPublicKeyAndEncryptMessage(xmlKeyData As String, fileName As String) As Byte()
		   		' Create a new RSA CSP in which to load the public key data from file
		   		Dim yourRSA As New [RSACryptoServiceProvider()]
		   		[yourRSA.FromXmlString(xmlKeyData)]
	

		   		' Encrypt a message and return
		   		Dim original As Byte() = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog")
		   		Return yourRSA.Encrypt(original, False)
	
End Function

Problem Example

In this example, the problem example assumes that the user simply does not use any means of encryption to transmit messages to the owner of the public key.

* Wherever an attacker can gain access to the data stream between the sender and the recipient of a message, the confidentiality of that message data could be compromised in transit.
* Unsecured wireless networks, management consoles for networking devices, ARP-spoof and poisoning attacks are all examples of mechanisms that a malcious inidividual might used to compromise clear text traffic.


Test Case

The following classes must be included in any project making use of the sample code provided above:

Imports System.IO
Imports System.Security
Imports System.Security.AccessControl
Imports System.Security.Cryptography
Imports System.Text
Imports Microsoft.Win32

Execute the following code to see a plaintext message and then an encrypted version of that message created using the public key.

Sub Main(args() As String)
		   		' Read public key into a string
		   		Dim [publicKeyXml] As String = "<RSAKeyValue>" + 
	
"<Modulus>tnLAgAJwXXxYj+2QPX6q/mHZZf23xSvvovoBlZ1Y7RbTlkY4N2nlcGxfR6mQcTTWKfWShQ7yEaX6rVfhhRhdaH
LCsg7g3AmW2BsoBxWUijD81ZeNKyWrw8t0gjnigNR46PqO1Xi7R9aAPgaluhuZBBgJK2wIAlRJSPlTr5OjDr4vJlZiAG/V
qmJVXioPfv1QI2hfLM86JgIcrD47L0K44tKwyhAj4PN1nsomjPeb0P9m9t3od/cyZGKkiJ1nwQwG02H/EXROaO6YFKb3xi
jNv69gvZLGcqssXs7Bs7CdzqmQvSylxuXkYz5bQG++raYWm4l056WhtIRG8mqQ==</Modulus>" +
"<Exponent>AQAB</Exponent>" +
"</RSAKeyValue>"

		   		' Encrypt a message using our key and write out the results
		   		Dim msg As String = "The quick brown fox jumped over the lazy dog"
		   		Dim encrypted As Byte() = [ReadRSAPublicKeyAndEncryptMessage(publicKeyXml,] msg)
	

		   		Console.WriteLine("Original:")
		   		[Console.WriteLine(msg)]
		   		[Console.WriteLine(ControlChars.Lf] + "Encrypted:")
		   		[Console.WriteLine(Convert.ToBase64String(encrypted))]
	
End Sub


Expected Result

Original:
The quick brown fox jumped over the lazy dog

Encrypted:
EPiXscCwYg7R/o35sNWqEKsJrdKNx7I6x3RA59IMelpFP8HOhD5qi2XLvuMPpran++4SmRvE69RRLwF1
9NbIWv2KUx9FUFa3qWfkAKD1jk/PtgnOWBLM8po3eibs1VkwWxMbcEJrGKEp5eFBle7v66jzmAsxJDlA
MNoFfj/U/4CgzalMB09/ZnpBcoCq07NipwHYQxKfanyUfMDUyvfN69sYtdOKodMon6VwA2GRkCv4rN4V
rHO+dloWL0hJlxgTVp19/X5oMigr3ZhqFURCETGppCS4KZ3uqwpO3LC5smSwLzNBZtdnjUm57OqWaeLo
D2GHhhvBdKvAcmYAABFYJw==


More Information

RSA is an algorithm for public key (also knows as asymmetric) cryptography in which distinct public and private keys are created. Encryption operations makes use of the public key while decryption requires the private key. This offers an advantage over symmetric cryptography because the secret key used to decrypt a message does not need to be shared in order to support encryption of messages to a recipient.

The RSA private key must be securely stored in order to maintain the confidentiality of data encrypted using an individual's public RSA key. However, the public key can be freely distributed by the owner of the key pair to anyone who wishes to send an encrypted message to that owner.


Additional Resources

* RSACryptoServiceProvider (.NET): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptographyrsacryptoserviceproviderclassctortopic.asp
* Cryptography (.NET): http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGGuidelines0003.asp?frame=true#pagguidelines0003_cryptography


Attributes

* Applies To: .NET Framework 2.0, VB
* Category: Cryptography
* Author: Jonathan Bailey



Return to HomePage
Microsoft Communities