Cryptography in .NET

Overview

Windows provides a Public Key Infrastructure (PKI) that allows us to store
certificates for encryption purposes. To access the this store we had two
possibilities in the unmanaged past: The CryptoAPI and the CAPICOM.

The Framework Class Library (= FCL) provies a lot of function
for encryption, but the current release doesn't provide any classes for
accessing the the certificate store. Fortunately a the
Web Services Development Kit (WSDK) Technology Preview adds this
functionality; later this will be included in the FCL itself. But in the mean
time you have to download the WSDK.

Asymmetric Encryption/Signature Example

The following code is the funcionallity of my submitted example. It assumes
that you have at least two certificates (with private key!) in your Personal
Certificate Store.

try
{
// GENERAL CODE TO READ THE CERTIFICATES FROM THE WINDOWS PKI INFRASTRUCTURE
//// BEGINNER-TIP: Start MMC (=Microsoft Management Console) and select "Add-in/remove Snapin"
// from the "Console" menu. Now press "Add.." button. Select "Certificates" in the list and
// press "Add" button. You have the choise to select "My user account" or "Computer account".
// Then press "Finish" and "Close" and start exploring the installed certificates...
// Each store has a "Personal" section with is BTW represented by the letters "MY".
// Also interessting is the "Trusted root" certificates, there you see all the Certificate
// Issuer that you trust, there is quite a lot and sometimes it's a good idea to delete
// all of them and only add the one you need or really trust, for security resasons.
//// Open private certificate store of current user
X509CertificateStore store =
X509CertificateStore.CurrentUserStore( X509CertificateStore.MyStore );
store.OpenRead();
// Read e.g. the first two certificate
X509Certificate sender = (X509Certificate)store.Certificates[0];
X509Certificate receiver = (X509Certificate)store.Certificates[1];
// Let's see who we are dealing with... - ps: not nessesary for the following code
string sender_serial = sender.GetName();
string receiver_serial = receiver.GetName();
//// SENDER-SIDE CODE
//// SENDER-SIDE: Extract own private keys and receiver's public key
RSAParameters sender_private = sender.Key.ExportParameters( true );
RSAParameters receiver_public = receiver.Key.ExportParameters( false );
// SENDER-SIDE: Asymmetric encryption with receivers's public key
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.ImportParameters( receiver_public );
byte[] cleartext = ASCIIEncoding.ASCII.GetBytes("test");
byte[] cipher = rsa.Encrypt( cleartext, false );
// SENDER-SIDE: Sign the cipher with own private key
rsa = new RSACryptoServiceProvider();
rsa.ImportParameters( sender_private );
byte[] signature = rsa.SignData( cipher, new SHA1CryptoServiceProvider() );
//// TODO: TRANSFER DATA OVER UNSECURE CHANNEL...
//// RECEIVER-SIDE: Get own private key and sender's public key
RSAParameters receiver_private = receiver.Key.ExportParameters( true );
RSAParameters sender_public = sender.Key.ExportParameters( false );
// RECEIVER-SIDE: Verify signature with sender's public key
//// Note: You are ONLY verifying the signature and NOT verifying the Certificate!
// It's corresponding to the CAPICOM call SignedData.Verify( CAPICOM_VERIFY_SIGNATURE_ONLY )
// I did not yet find out how we can use the .NET library to verify the Certificate
// against the issuer-chain. If someone knows how to do this, and not using interop
// and the SignedData.Verify( CAPICOM_VERIFY_SIGNATURE_AND_CERTIFICATE ), I would be
// very, very, very happy - because this is a requirement in the software I'm developing
// currently and if we can't do that I have to do CAPI-interop :-(
// At the moment I think that there is no simple function call for this and this s***s.
// Maybe it's possible to walk throw the chain-of-issuers and validate the fingerprint
// this the public key of the issuer. But I don't know enough about that....
// ANY HELP TO THIS POINT IS MORE THAN WELCOME
//
rsa = new RSACryptoServiceProvider();
rsa.ImportParameters( sender_public );
if( rsa.VerifyData( cipher, new SHA1CryptoServiceProvider(), signature ) )
{
// RECEIVER-SIDE: Asmymetirc decryption with own private key
rsa.ImportParameters( receiver_private );
byte[] cleartext_after_decription = rsa.Decrypt( cipher, false );
// Check result
Debug.Assert( ASCIIEncoding.ASCII.GetString( cleartext ) ==
ASCIIEncoding.ASCII.GetString( cleartext_after_decription ),
"Ups, the cleartext input is not equal the cleartext output..." );
}
else
Debug.Assert( false, "Ups, check signature failed!" );
}
catch( Exception e )
{
// NOTE: the following exception, that may occure during 'ExportParameters( true )'
//// System.Security.Cryptography.CryptographicException
// "Key information could not be exported from the cryptographic service
// provider (CSP) for this implementation." }"
//// Can have one of the following reasons:
// + The certificate was NOT imported with the flag "Mark the private key as exportable"
// + The type "SSL Server Authentication(40)" and is in a CurrentUser store and not in
// the LocalComputer store. See certificate details in the MMC under "NetscapeCertType".
// IMHO: This reason is very wicked and I don't understand it!!
Debug.Assert( false, e.ToString() );
}

Note: The X509Certificate class provides the function ExportParameters and the
boolean parameter defines if the private key has to be submitted as well.

A quick note

Favorite person names for encryption examples are Alice, Bob and mean
Steve. If you like to see how they are doing in .NET, search your
MSDN examples
for the excellent example file called PublicKey.cs!

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.

Share

About the Author

Comments and Discussions

I am no expert in cryptography , but I had to do the digital signing of emails for some purpose I wrote the code below which constructed message usind CDO and then signed data to be sent with CAPICOM and then send teh data. Well the problem is : when I send email using code below it says "Message has been tampered with" , though there's no such thing of course ( at least while trying it). I guess I am doing something wrong with conversions but cant be sure, except that error message all other things work ok, mean certificate is verified against chain and etc.. but as I said the digitally signed message I send seems to be corrupted.If anyone can help I will be very pleased. Ur sincerely Ray

Here is the code//***************************************************************************

Ok I have solved the problem that I sketched aove, the problem was with encoding. Now I can sign and send messages, but I cant send the Signed(message+attachment) , that is text and attachment I want to sign , but it gives me "the message has been trampered with" staff, so tell me what am I to do?

Hi friend .I faced the same problem ,I remember struggling with line endings for a long time (it seemed that I put one extra line ending ).
I send here the modified code of what I wrote before and its code (at least work here ) hope it helps.
Sincerely Ray

' Set the messages content type, this needs to be done last to ensure it is not changed when we add the BodyParts
oSignedMsg.Fields.Item("urn:schemas:mailheader:content-type").Value = "multipart/signed;" & vbCrLf & "protocol=""application/x-pkcs7-signature"";" & vbCrLf & "micalg=SHA1;boundary=SIGNEDBOUNDARY"
oSignedMsg.Fields.Update

' Signing Was sucessfull
SignMessage = True

' set the from field based off of the selected certificate
oSignedMsg.From = oSigner.Certificate.GetInfo(CAPICOM_CERT_INFO_SUBJECT_EMAIL_NAME)
oSignedMsg.To = tostr
oSignedMsg.Subject = subjectstr
oSignedMsg.Fields.Update

Yes as u said the StrConv is the built in of VB 6.0 and it wont work for vbscript and vb.net (though in vb.net you have counterpart for that function doing the same thing).
I sent the vbscript version of the function too in the code I submitted previously (at the bottom of the page maybe u missed that). What it does is this : using the ADODB stream it converts the unicode characters to ascii and back. You should use that custom function in vbscript code because the built in StrConv is not available in vbscript (at least its how I know it to be)

P.S: also u can convert the code to vb.net but, theres a big but in that not technically but in principle. If you are writing a web application the certificate you are trying to access is on client machine and not server. So the only solution I saw is to write a script for it, because theres no way of bringing the certificate (wth the private key) to server (its not right thing to do ). So I guess if u are writing the web application you should do it in script.

I am facing error when signing mail with embedded image. To embed image, it need to be a Part of the main body. If you put it as a Part of a Subpart (I mean, it should be oSignedMsg.BodyPart.AddBodyPart and not oSignedMsg.BodyPart.BodyParts(1).AddBodyPart) it will embed as well as show as an attachment.

Issue is, if we put image as part of a subpart signing is fine; Outlook validates it. Problem is it will embed the image as well as show it as an attachment. If we put it as part of body, signing fails; It is not recognised as a signed message.

Good article, nice and short and to the point. One reminder, URL to "Web Services Development Kit (WSDK) Technology Preview" is broken.

Also, I can do all this without WSDK - using just System.Cryptography? I'm new to this. I am just looking for examples (.NET samples):
1. sign/hash/encrypt data (covered in this article)
- both PPK and classic symmetric algo.
2. Also want to know how to "publish" your public key so receiver decrypt payload and verify signature (in your sample, client and receiver on same machine/process.) So, am I talking about exporting key/key blob? A handle to a key is meaningless on a remote machine. (this is NOT covered in the article)
3. retrieve certificates from cert stores (covered in this article)
4. add cert (makecert.exe or MMC/3rd party: I'm alrite with this.)

Any good articles? I want to do this all .NET - but as you mentioned, you don't get .NET support in dealing with cert stores. Is that still true?

That's old news but I have a comment to make on the code above. If you don't export and do import your certificate key directly into RSA by using the code below to instantiate the RSACryptoServiceProvider class you overcome many problems (such as un-exporable keys).

1. How do I extend this code to encrypting entire files intead of blocks of few bytes (limited by rsa.encrypt). Should I come up with a random key for 3DES, encrypt the file with that and then append the key as RSA encrypted?

2. The code doesn't work for smart cars where private keys are located at the chip. How do I change the CSP to smart card software vendor's CSP (that I have) or is there some other way to go?

I'm a newbee at encryption. I've got a task that I'm looking for advice on.

In my company, everyone was issued a unique certificate file (XXX.CER). What I need to do is :
1.) Read the certificate from the floppy drive. (Something like FCLX509.X509Certificate FCLcer = WSEX509.X509Certificate.CreateFromCertFile(@"A:\IAmEmmetSmith.cer")

2.) Extract the person's name. (Which I know how to do.)
3.) Make sure the certificate is valid. (Only 1 Emmet Smith with this particular certificate that works on our server.)

I don't know how to #3. Help!

I've seen sample code like this:
X509SecurityToken token = new X509SecurityToken(cer);
token.Verify();
but I imagine that I need to match the certificate file with the certificate on the server.

I used the above code. It is failed to verify my self signed certificate. The certificate is created using the command "makecert -r -pe -cy both -n "CN=MyName" -ss Root
The error message is as following:

Microsoft.Web.Services.Security.SecurityFault: An invalid security token was pro
vided ---> System.Security.SecurityException: The certificates trust chain could
not be verified: CERT_CHAIN_POLICY_STATUS is 2148204809.
at Microsoft.Web.Services.Security.X509.X509CertificateChain.Verify()
at Microsoft.Web.Services.Security.X509SecurityToken.VerifyTrust()
at Microsoft.Web.Services.Security.X509SecurityToken.Verify()
--- End of inner exception stack trace ---
at Microsoft.Web.Services.Security.X509SecurityToken.Verify()
at Codeproject.Cryptography.CryptographyApp.VerifyCertificate(X509Certificate)

I m trying to build a secure .NET web application using Digital certificates.
I created a couple of test certificates using makecert utlity. I also have CAPICOM installed on my PC.
Can someone suggest how I should proceed further?
What all needs to be done in order to send as well as receive secure data?

I am wondering if CAPICOM is still necessary. Right now I am doing COM+Interop to CAPICOM from C# because I have PKCS#12 (aka PFX) files in my personal store.

I take some data, use the private key in the PKCS#12 cert to sign it, and then use the receiver's public key in an X509 to envelope it. Then I dump it in a queue.
The receiver de-envelopes with the private key in their PKCS#12, and then uses the sender public key in an X509 to verify the signature.

Are you saying that this isn't necessary with the WSDK stuff and your code? It looks like the MS stuff only handles X509, which has no support for private keys. I am little confused.

That's true, for the X509Certificate class that is installed with .NET.

But this example uses Microsoft.WSDK.Security.Cryptography.X509Certificates.X509Certificate class that comes with WSDK (see link in the artilcle). After you installed the WSDK, you can import the WSDK-dll and use the Microsoft.WSDK.Security... namespace.

Note: To export the private key of a certificate, the certificate has to be marked as "exportable". This can be set during import of certificate with the MMC plugin.