Just Code it!
Header

This post is a tutorial that will explain hot to write a simple C++ code that can be considered the starting point for any other program you intend to write in C++ with the intention to use a MySQL Database.

In order to connect to MySQL from C++ we will use some libraries specifically designed for this purpose.

Despite the concept seems simple, there are a series of gotchas and configurations that can put off the task many people, increasing the amount of work needed and not necessarily forecasted.

This tutorial will reach the goal starting essentially from scratch, where the environment needs to be completely configured… even without Visual Studio!

While writing this tutorial, I decided to split it in multiple sub-posts because of the amount of information I ended up collecting. Doing this will remove some of the noise around the main topic and will allow to follow the post and the specific sections even for people with different requirements that have already available some of the systems I am going to describe.

As a reference, these are the additional posts:

 

Enough said, let’s start the journey! See you at the end of this. Happy reading.

mysql-connector (1.1.4) – Download

First things first… let’s immediately download what we are really interested in, the C++ libraries (source) that will allow us to connect and interact with a MySQL database.

Open the browser to the MySQL website and navigate to the page with the information about the connector:

http://dev.mysql.com/downloads/connector/cpp/

Select the “Source Code” option from the drop-down menu:

Download the generic Windows version:

In the following page select your preferred download option or just download it using the link at the bottom of the page:

Let’s remember the warning reported on the website:

Warning
One problem that can occur is when the tools you use to build your application are not compatible with the tools used to build the binary versions of MySQL Connector/C++. Ideally, you need to build your application with the same tools that were used to build the MySQL Connector/C++ binaries. 

 

Create a folder, for example “C:\libs\” and extract the archive in there.

The structure should look like this:

In order to build the source code for the connector libraries we need to download CMake.

It’s time to switch to the first sub-post if you need to perform this step and install CMake (CMake Installation and usage (Command Prompt Console and GUI)).

Jump to this post and see you here once you are ready to continue (I would suggest you to follow just the initial part of the tutorial, limited to installing it. The remainder will be useful later on and will probably not work on your system if you don’t have everything else already configured): CMake Installation and usage

Back from CMake Installation

I will assume that you have CMake installed on your system now.

mysql-connector 1.1.4 – Build – First Potential Problem (Missing Visual Studio)


If we try to run the CMake command to generate the Visual Studio solution from the mysql-connector code we could potentially immediately receive an error.
Let’s try this using the Command line:

C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

If you don’t have the C/C++ compiler then you will see this error:

Pay particular attention to the lines:

If that’s the case, what you need to do is installing Visual Studio.

Visual Studio (C++ 2010 Express)

Let’s download Visual Studio (Visual C++ 2010 Express is ok for us)
Go to the website:
and find the Install Now link:
Install it executing the installation file (vc_web.exe) downloaded.
Then try again!

mysql-connector (1.1.4) – Build – Second Potential Problem (Missing Boost Libraries)

If we try again now:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”
This time it should go further and complain about the (potential) next problem:

 

The main issue is now:

The problem now is that in order to build this code you need to have installed the BOOST libraries.
If that’s the problem you see as well, then you can happily jump to the next sub-post where is explained in detail how to install and configure boost libraries: Boost Libraries Installation
See you when you are ready to proceed!

Back from Boost Libraries Installation

You should now have a system with CMake, Visual Studio and Boost Libraries installed and configured. Time to continue!

mysql-connector (1.1.4) – Build – Third Potential Problem (MySQL not installed)

Go back into the connector folder and execute again:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

NOTE:

If you decided at any point to move the folder after executing cmake the first time you will potentially see an error:

To quickly fix this, just remove the file “CMakeCache.txt” and run cmake again.

If you don’t have MySQL installed on your system, then you will probably see this error:

The main indicator for this problem is the line:
If that’s what you see as well… well, you know what’s coming. Yep, another sub-post: MySQL Service, Workspace, Users and Tables
Jump to this post and you can read for now just the initial part that covers the download and installation of MySQL.
The rest of that post will show how to create a database, user and table that we will here, but you can go back to that section later on.

Back from MySQL installation

If everything went as planned until this point you should have CMake, Boost libraries,Visual Studio and MySQL installed and ready to rock.

mysql-connector (1.1.4) – Build – Creating the Visual Studio Solution

Now we can go back into our connector folder and try once again to recreate our Visual Studio Solution.
Yhou can follow this step in the CMake tutorial if you want (where it is explained how to obtain the same result using the command line or the GUI).
This is an extract of it, where I will show only the command line option.
If you run the same command again:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

You should finally succeed in this step, obtaining:
Now, if everything went as planned, you should be able to see a solution file (and other files as well) into your connector’s folder:
Now we can finally open the created solution (MYSQLCPPCONN.sln) with Visual Studio!
Simply double-click on:
MYSQLCPPCONN.sln

Build MySqlCppConn.sln – Debug

In Visual studio, set the configuration to DEBUG and try to Build.
What should happen is that you will see a series of errors:
ERRORS:

Open the properties for the project “mysqlcppconn“. Right-click on it and select “Properties”:

We can do this using different techniques, but I want to use one (even if it is not my preferred one) just for a change :).

 

Make sure to be in the configuration “Debug” and go in the section:

Common Properties -> Linker -> Input

 

Open the “Additional Dependencies” drop-down list and click on “<Edit…>”:

Substitute the entry:

  • C:\Program Files\MySQL\MySQL Server 5.6\lib\mysqlclient.lib
with:
  •  C:\Program Files\MySQL\MySQL Server 5.6\lib\debug\mysqlclient.lib

If you build now you could receive another error:


Open the project properties for the project “mysqlcppconn-static

Go in the section:
Common Properties -> Librarian -> Command Line
and change the additional options from:
  • C:/Program Files/MySQL/MySQL Server 5.6/lib/mysqlclient.lib
to:
  •  “C:/Program Files/MySQL/MySQL Server 5.6/lib/debug/mysqlclient.lib”
including the quotes
Build again and everything should be ok now!

Build MySqlCppConn.sln – Release

For the release build the only fix I had to do was only the “Additional Options” section in the Librarian -> Command Line

section for the “mysqlcppconn-static” project (in Release configuration).

Add the quotes to:

  • C:/Program Files/MySQL/MySQL Server 5.6/lib/mysqlclient.lib
Also in this case you should receive a successful compilation:

 

Libraries

If you open now the window explorer in the connector folder, in the sub-folder “driver”:
C:\libs\mysql-connector-c++-1.1.4\driver
you should see the two build folders “Debug” and “Release”:
Inside these you should find at least the three files:
  • mysqlcppconn.dll
  • mysqlcppconn.lib
  • mysqlcppconn-static.lib
We are ready to use it finally!

Creating a DB

It is finally time to create a database in MySQL that we will use in C++.
You can refer back to the post already highlighted previously (MySQL installation and Usage) and continue to follow it from where you left it until the end.
In that tutorial I explain how to create a sample DB with a sample user that will have access rights and a sample table that we will be able access from code.
When that system is ready, is time to jump into the final step!

Coding – Create a new Visual Studio Solution

In Visual Studio create a new project (I selected a simple Win32 Console Application)
Right click on the source folder and add a new cpp file:
Let’s give it a simple name (the very original “main.cpp” :P):
You should see the new file added:
Before writing any code, let’s configure our environment setting up the folder and libraries that we need to use/reference in order to successfully build our app.

Coding – Configure the Environment


Open the properties window of the project and go to the settings page:
Configuration Properties -> VC++ Directories
And edit the entry:
Include Directories
Make sure you are in the “All Configurations” configuration:

Edit it adding the lines:

C:\libs\mysql-connector-c++-1.1.4\cppconn

C:\Boost\include\boost-1_56

Edit then the Library Directories property, adding the line:

C:\libs\mysql-connector-c++-1.1.4\driver\$(Configuration)\

Edit then the property in:

Configuration Properties -> Linker -> Input -> Additional Dependencies

adding the line:

mysqlcppconn.lib

One last step you may need to do is copying the “libmysql.dll” and “copy “mysqlcppconn.lib” into your output folder.

Just open the properties to:

Configuration Properties -> Build Events -> Post-Build Event

Then edit “Command Line” and type in this (or the equivalent line that you need in order to copy the missing dll to the output folder):

copy “C:\Program Files\MySQL\MySQL Connector C 6.1.5\lib\libmysql.dll” “$(OutDir)”

copy “C:\libs\mysql-connector-c++-1.1.4\driver\$(Configuration)\mysqlcppconn.dll”  “$(OutDir)”

Remember to edit All Configurations:

Finally it’s time to code!

Coding – Code: Connecting to MySQL

Open the “main.cpp” and let’s put some code.

The first simple code will just test the library, connecting to the DB (our one) using the user that we previously set-up in MySQL Workbench.
Remember to configure correctly:
  • The database address (and port)
  • The User and Password for your user
  • The Database name (that contains the “contacts” table)
That’s the simplest code with some error handling:

If your run this code and you didn’t set-up correctly one of the used parameters, then you will see the error text (without crashing). If that’s the case, check your parameters and verify that you will see the “Connection to the DB established!” string.

Coding – Code: Connecting and using the DB

For the final part of this post we are going to see how to connect now to our DB and retrieve and print the data from our table!
The new lines are the ones that follow the connection established message and few extra includes.
I will omit any exception handling to keep the code short and simple.
This is the final code:

If you build and run the code, you should be finally happily able to see the rows that we entered in our table using MySQL Workbench!


 

That’s all!

 

Of course you can now play around with it inserting, editing, removing entries. For these functionalities and more advanced one I point you to the official website and in particular to the Developer Zone:
Please Link and comment if you found this interesting or useful.

As for other posts (see Boost Libraries Installation), this post is actually a sub-post I made while I was writing a larger post where I explain how to download and use MySQL connector C++ libraries (MySQL C++ with mysql-connector).

That post soon became pretty big due to the amount of stuff you need to configure in order to achieve the goal, therefore I decided to split it in smaller posts that on one side are useful on their own and on the other helps in keeping the main post they came from slightly smaller and easier to follow. Because of this I will keep these posts quite short.

If you are interested in this post as well, you can find it there:

For this example I will use MySQL Connector for C++ as a sample to show the usage of CMake to generate Visual Studio solutions.

Let’s start!

 

CMake (3.0.2) – Download and Install

In order to build the source code for the connector libraries we need to download CMake
Go to the CMake website:
and download it:
Select the Installer in this case:
Execute the installer. I selected the option to add it to the system PATH for an easy access:
Just go Next until the end and Install it.
CMake (3.0.2) – Test
To test that everything is ok with cmake, open a command console and go into the folder where we extracted the connector code and execute:

C:\libs\mysql-connector-c++-1.1.4>cmake

 

We should see this output:

We can generate the Visual studio project in two ways:

  • Using the GUI
  • Using the command line

 

 

CMake (3.0.2) – Usage from Command Line to generate the Visual Studio Solution
At this stage, if you are following the MySQL connector tutorial () you want probably to go back to follow the rest of the tutorial, where you will install first all the required libraries and systems that you need in order to successfully execute the next command.
If you did instead all the required step and everything is correctly configured or you want just to see an example of the usage of CMake for this purpose, then keep reading.

Now we can go back into our connector folder and try once again to recreate our Visual Studio Solution:
C:\libs\mysql-connector-c++-1.1.4>cmake -G “Visual Studio 10”

Obtaining:

 

Now, if everything went as planned, you should be able to see a solution file (and other files as well) into your connector’s folder:

You can then open the solution and continue from there.
CMake (3.0.2) – Usage from GUI to generate the Visual Studio Solution
An alternative way to generate the Solution file is to use the CMake GUI.
Launch the cmake-gui from the start menu:
In the window that opens select “Browse Source…” button and locate the root of your project.
I will select the one where the code for MySQL Connector has been extracted:
Copy the same path for the binaries, then click on “Generate” (or Configure) and select the IDE you are interested in.
I will select Visual Studio 2010 for this example.
Click “Finish” when ready:
Everything should complete successfully (pay particular attention at the bottom window without being too much scared by the red entries in the main window):
If you try to click once again (or why not… a couple of times as well :P) on the “Generate” button, all the red should disappear from the main window:
Anyway, despite the colouring, you should still be able to see your new solution file generated and ready to be opened in Visual Studio.
Now, if were following the MySQL connector tutorial (MySQL C++ with mysql-connector) you can go back and follow the remaining part of that tutorial.

 

Comment or Leave a Message

Please Comment or Leave a Message if this is what you are looking for or if you have any question/comment/suggestion/request.

If you are reading this post it is probably because you have some trouble trying to have your application to run on a system where some COMs dependencies don’t seem to be happily resolved, or because you can’t afford to register the COMs at all (policy?)… or if you don’t have any COM problem at all, well… keep reading. The DLL Hell is always behind the corner.
Because the problem is quite annoying when happens, I provide at least four solutions so that you can choose the one you find more comfortable to use :). Let me know which one you prefer and if you know other alternative ways to do it as painlessly as possible.

The Problem
Imagine to have a simple application that references a COM object. You try to build your COM and then your app, and eventually you try to run it on your machine and… it works! Good! So you happily go and copy your App and the DLL of the COM in a single folder on a second machine and… BUM! Your App crashes without hope.
So, what’s going on?
The problem relies on the fact that when you use a COM DLL (with Early Binding), you are somehow coupling your App with a precise version of your COM library. This means that if one day you or someone else upgrades the COM DLL, then the App will still continue to work using the original COM it was binded to. What really happens is that your App will not simply try to locate the DLL (using only its name) in the current folder and then in the PATH environment variable, but will actually use a GUID (the CLSID) to locate the COM DLL in the Windows Registry and from there locate the file in the file system. GUID stands for Globally Unique IDentifier (while CLSID is the CLaSs IDentifier) and is automatically generated for you when you create the COM object and automatically used when you reference your COM from your App. If you want to see how to use a COM you can have a look at my other post ([intlink id=”114″ type=”post”]Create a .NET COM and use it in Unmanaged C++[/intlink]).
This GUID is then the only thing that the App will use to locate the COM DLL, and in order to make this work you have to “Register” your COM classes as we already know.
So, what if you don’t want to register it?

Sample Scenario
Let’s assume that we have a couple of COM DLLs with one sample Object each and both with a simple (different) method defined. In my example I have these:

  • MyPippoCOM COM with a SillyAdder class (CoClass)
  • MyOtherCOM COM with a SmarterMultiplier CoClass
  • TestApp exe that uses the two previous COMs using Early Bindings

In TestApp I instantiate the objects using the ProgID.

The Tool
Fortunately Microsoft came up with a (almost) simple solution.
The trick is create a *special* file that will tell to our App how to behave and where to look for what it needs. This file is the “Manifest”.
As a brief description let’s just say that this is a simple XML file and in there we can specify where are the DLLs that we want to provide to our app, bypassing the normal searching behaviour.

The Problem of the Tool
The problem here is that writing what you need here is not always (actually almost never) easy. In fact, in order to describe the COM that you App will have to use, you must “describe” it, specifying all the GUIDs, ProgIds (if you need it), and other nasty details that are generally (and fortunately) auto-generated for us when we Create and use a COM in a normal/standard way… So why do we have to suffer now? Fortunately we don’t, we are safe this time as well :P.

The Basic Solution – Understand What’s Going On
Based on Microsoft Documentation, the way to create a manifest for your DLL is to use the Tool mt.exe (this is the Documentation).
With this tool you can generate the manifest that you will have to use with your App if you want to achieve our goal.
For example, considering our MyPippoCOM.dll DLL, we could do something like this (from the command prompt, in the folder where the dll and tlb files are stored):

This will generate a file named “mySample.manifest” that, in my case, will contain something like this:

At this point you could do the same thing for the other DLL and then (only after), create the manifest for your app.
This is because with this tool you can only specify one dll and tlb when you generate a manifest and consequently you cannot create a manifest with the data for both DLLs in one go. Fortunately though this tool allows you to merge multiple manifests! So you could use this as final step toward the creation of the Application manifest. I said “toward the creation” because unfortunately the manifest that you will have at the end of this process will be incomplete and could contain some errors as well if you didn’t follow exactly my example and you specified the dll and tlb file using an absolute/relative path instead. I’ll explain later how fix this. For now le’s see how could you merge the two manifests:

The result will be a file named “merged.manifest” that in my case will contain this:

As it stands you cannot use it directly. You need to rename it, fix a couple of things in it, adding some missing informations and you need to build the TestApp without embedding its manifest.
So, first things first. Go back in VS2005 and build our TestApp changing one setting. Open the project’s properties, expand the section “Manifest Tool” and enter in the “Input and Output” entry. In the option screen on the right set “Embed Manifest” to “No”.
Now you can build the project again and this time a file TestApp.exe.manifest (in my case) will sit next to the executable.
Now open it. It should look like this (the dependentAssembly section will include the proper assembly based on which type of build you selected, debug or release):

Now it is just a question to grab our previous merged manifest (from the two COMs) and copy all the content that appears inside the “assembly” tags into the TestApp.exe.manifest, just before the assembly closing tag. In my case this will be the result of this step:

Ok! Almost there.
The final step is to add something that mt.exe doesn’t add for us but that I like to have, the ProgID attribute. You have to do this by hand unfortunately. Just add this attribute to any comClass tag. The final result in my case is this (I optimised some tags a little bit as well):

Note that the ProgID should actually contain the version number as well (e.g. progid=”MyPippoCOM.SillyAdder.1″), but the other version does work if you don’t specify this number when creating the object in your code as in:

That’s all for this first long manual version.
There is a way to skip some steps and do it slightly more automatically.

The Semi-Practical Solution – The Slightly More Automatic Way
A way that I found helpful to adopt is to make usage of the post-build steps feature.
To keep it short and simple, what you can do is edit the post-build event for both of your COMs projects, adding somethig like this:

(and similarly for the other COM).
This will generate automatically a manifest named “manifest.manifest” (nice name uh? :P) in the project output folder.
Then edit the TestApp project’s properties, writing in “Manifest Tool | Input Output | Additional Manifest Files” the location of any manifest that you want to merge.
Those two settings will essentially automate the creation and merge of the manifest that we previously did manually!
You will have to do the final fixes anyway. Maybe you can try to automate this as well :).

The Practical Solution – The Fast Way
I found a way to cheat and generate the manifest with even less work. It is sort of cheating, but it is fast and works! :).
Instead of opening Visual Studio 2005, open VS2010 and create a new project. Just any project, a console app for example.
Now right click the References tab in the solution explorer and select “Add Reference…”.
In the window that will pop-up select “Browse” and navigate where the first COM DLL is located and add it.
Repeat the same process for all the other COMs.
When the References list is completed, expand it and select all the COMs that you just added.
Go in the “Properties” window of the selected references entries and change the value of “Isolated” to True.
Job Done!
Now when you will build the project a .manifest file will be automatically generated and it will contain the correct XML for both COMs.
mine looks like this:

Notice that it contains the ProgID attribute with the version number (“.1″) at the end of the string (see: progid=”MyPippoCOM.SillyAdder.1”). You will have to remove it if you don’t specify it in your TestApp application.
Apart from this, you can directly use this as input manifest for the TestApp saving even more time! :) (you can consider to change the assemblyIdentity attribute if you do this).
NOTE: In order to apply this solution the COMs must be registered on the developer machine. This must be said just in case you did some previous steps and you unregistered them and you didn’t rebuild the projects ever after.

The Speedy Solution – The Last Tip!
There is a final tip to avoid even more typing. The only thing to prepare is the merged manifest in the way you prefer and use this one as Additional Manifest File in the Input and Output section of the Manifest Tool in the properties of the C++ TestApp project. Then, instead of setting the Embed Manifest to “No”, Leave it to “Yes”.
This will generate the application exe without any needed manifest and this is ready to be executed side-by-side with the COM DLLs.
No more editing, no more problems :).

Note about VB6 COMs
If you have VB6 COMs the previous method will still work really well (even with a correct ProgID), but if you want to explore even alternative ways, there is an interesting tool that you can try to use to generate the manifest for each specific COM.
You can find the tool here: Make My Manifest
What it does is essentially create a manifest for any VB6 projects (not only COMs) generating a complete manifest with all the project’s COM dependencies.
So this is more exhaustive than our single C++ COM manifest and this means that if you have multiple VB6 COMs that uses others COMs, then the manifests could contain common elements and thus the merge should take care of this. But for the rest it is a quite nice tool to use, so give it a try.

Conclusion
The DLL Hell is not a random name and what I tried to cover in this post is just the tip of the iceberg.
I wanted to write this because I found quite difficult to gather the practical information that I ended up discovering personally through a long series of frustrating experiments in order to properly understand and faultlessly solve the main problem.
I hope that this helped you and you found it interesting.
Let me know if you discovered other ways to solve it or if you have any suggestion/question/information that you want to share ;).

Comment or Leave a Message

Please Comment or Leave a Message if this is what you are looking for or if you have any question/comment/suggestion/request.


So, now you (actually Me) want to encode and crypt something in C++ and then (maybe after a network message), decrypt and decode this info in C#.

Let me explain exactly what I mean with encode/decode, crypt/decrypt.

We use the user’s two public/private key pairs to crypt/decrypt a session key that we will use to encode/decode a message. If all this make sense to you then let’s start.

First of all, let me answer one natural question: “Why all this?”

The reason of the double-step procedure to encode a message is due to two major reason:

  • crypt/decrypt (or signing and verifying) with an algorithm for public-key cryptography such as RSA (the one that I am using), uses a key pair, where one key is used to crypt some data, and the other (asymmetric) key is used to decrypt it. The things can actually work in both ways and in one case we will talk about signing and verifying.
    The protection here is very strong but the cost is resources, especially time. The algorithm is slow compared to others and for this it is not suitable for protecting a large amount of data. Another reason seems to be security itself, where many blocks encrypted with the same RSA key can help an attacker to reach his intent.
  • encode/decode instead is achieved using a symmetric key algorithm that can be very fast and if it is a stream cipher, it works great with streaming data :). I will use RC4 for this.

The Scenario

Two PC, connected through internet, where one behave as a server and the other is the client.

We assume that the server contains (well protected) its private and public keys that it will use to sign and decrypt some data that will go to or will come from the client.
For the client we assume that he knows the server’s public key and that he will use this to verify and crypt the data that he will receive from or that he will send to the server.

More about the Key Pair and Session Key

With Windows you can store/retrieve user keys (key pair) using the Crypto API. With it you can manage machine or user key in a quite simple way.
On the server we will use this API (in C++) to generate/retrieve (and then store) our machine key pair and we will tell the client our public key.

On the client will create a session key (C++) that will be used to encode a message with RC4.
Because the client knows the server public key, he will then use this to encrypt the session key.
Once this is done, the client will proceed to pack the two things together (encrypted session key plus the message) and send the packet to the server.

The Server at this point will save the message in a file, because we want to have more fun later on.

In fact, to make things more interesting then we will create a .NET (C#) project that will retrieve the same key pair previously stored, reads the file, imports the session key and decodes the message. All this in pure .NET.

Does it not seem fun?

To simplify stuff I will not use any network code and I will assume that the data are passed somehow between client and server. This can be network, file, or whatever (DB, mind power,…).
The only storage that I will use will be a file (the encrypted file) to allow a simple code in C# to open it and read and decrypt its content.
To simplify the code and shrink it to the fundamental parts I will provide code snippets that are mostly implemented as simple methods (C style) and I will assume the presence of some globally scoped variable (that should really be class scoped variable in a real environment). This will hopefully simplify the understanding of the concepts without losing the focus tracking the objects relationships.

Let’s start then.

Initial Server Code (C++)

In C++ we can easily use the Crypto API to do all we can (reasonably) think about when we want to protect our data.
This is available including “wincrypt.h” in your code.
The first thing to do is acquire the context where our secret keys are stored. This can be easily done with a code such as:

After this we can retrieve our exchange keys from the container. If the keys doesn’t exist I will create a brand new pair. This code does exactly this:

Happy with the result the next thing to do is to export our public key and give this to our client… or everyone… after all is a public key!
In my sample code I will use a memory buffer. The important thing here is that we are not here to cheat and this buffer will be the only thing that we will give to the client code pretending that it is a completely separate application. The export looks like this:

If everything is fine until now we can temporarily leave our server and switch to our client code.

Client Code (C++)

Because we are still working with Crypto API, the pattern is similar and so the first thing we have to do is acquire the container context in the same way we already did for the server.
The only difference is that we will use a different container to continue simulating a separate environment:

We can then import immediately the server public key:

The initial “handshaking” is completed now! The server is configured with his Key Pair and the client has received the the public part of this pair.

The next move is in client’s hand now. It has the freedom to choose a session key that will be used to encode a secret message.
For this task I am simply generating a brand new session key, especially generated for the algorithm that I will use to encode the message:

With this key I can finally encode my message!

Cool! The message is now protected… well, almost. In order to complete the transmission of the encrypted message, back to the server, we still need to take care of a few more details.
The first one is related to the protection of the session key itself. The server needs it in order to decode the message, but for sure we cannot send it as it is otherwise all this messing around with keys would be just a waste of time (human and cpu).
As already mentioned (and I hope obvious at this point) we will send our session key encrypted with the server public key. The server, and only the server, will then be able to decrypt it.

Enough chatting, let’s go to encrypt the session key then:

In my sample scenario I will simulate the transmission of the encrypted message using a simple file where I will write all the server needs to successfully decrypt the message.

My main focus here is to write a C# server that will be able to do this.
Anyway, just to complete the circle in the C++ world, I will add few more lines that will show how read and decrypt the same message in C++ as well, although I will not follow the same path and I will just continue to use memory buffers, just to avoid to add more details that are not relevant for what I have in mind now. If there is the need I will write another side article for it.

This said, let’s go back to our server (C++).

More Server Code (C++)

Assuming the message as received together with the encrypted key the first thing to do is decrypt the key of course:

As a result we will have another key object that can be used (at last!) to decrypt the message:

Job done! (in C++).

The last (really) thing to do is to create the file that will be used by the C# server.
I will use a single file where I will store both the encrypted key and the encoded message. To keep things a little bit more interesting (and realistic) I will write few bytes at the start of the file to communicate the size of the key.
Because we already have all we need, we can simply create a new file and write this info as described:

If you want to do some cleanup (and you should), remember to release the keys and the context when we don’t need them anymore.
This can be done easily in this way (this assumes that the keys are null if not initialised):

We are ready to switch to C#!

Server Code C#

The server here has to do basically the same things that we already done in C++, but in a slightly different way. In order to retrieve the Key Pair (I am not considering the creation of it in this context) we can use an RSACryptoServiceProvider object specifically configured (with a CspParameters object) to access the same server container we used in the previous app. You can find those classes in System.Security.Cryptography.
I will configure it to use the same RSA algorithm and forcing it to retrieve existing keys without attempting to create a new pair.

This is how we can do it:

We need something to decrypt now. I will use the file that has been created in C++ reading all its content in specific objects:

Once identified the encrypted session key we need to use the RSA service provider to decrypt it.
The only awkward things here is that the .NET encryption algorithm swaps the bytes after encryption (and before decryption) and we will have to take care of this directly, because this key was encrypted by the Crypto API in C++. Another thing to consider is that the encrypted blob doesn’t simply contain the encrypted key but some extra informations about the version, the algorithm to use with that key and the algorithm used to encrypt the key itself. I will not go into any detail for this here and I will instead jump in the session blob, straight to where the encrypted key is stored and use it (we already know what kind of key we generated for this toy app).
The encryption is then as simple as doing:

If everything is correct we will not receive any exception and the original session key is in our hands.

Let’s just use then to decrypt the message… well… no unfortunately.

In .NET there is no implementation of the RC4 algorithm that we used to encode the message.
Although annoying, this is not a big issue because its implementation is not so complex and can be easily hand-crafted.

I will not cover this algorithm in this post (but I will do soon in another one. Update: the post is available here: RC4 Cypher Algorithm in C#) and I will instead assume that you have access to a class/method that takes care of the algorithm details, providing a simple method to decode a message with a specific provided key.
If this is true we can then simply complete the task in this way:

Display the decoded message and jump of joy :).

Final Notes

Wait a second… nice, but… our keys? What if I want to cleanup the keys I generate with this sample code?
Correct. It would be nice to do some housekeeping when we are done with this.
In C++ we can remove out keys from our test container very easily. Sometime it is so easy that risks to be dangerous, but we know what we are doing now :).

The same thing can be done as easily as this in C# (actually it is even easier than C++):

If you try to run the C# server code again after removing the keys you will obtain a CryptographicException “Keyset does not exist” (as expected).
This will give you the knowledge that you correctly did your house-keeping :).