tags:

views:

788

answers:

5

I'm no crypto expert, but as I understand it, 3DES is a symmetric encryption algorithm, which means it doesnt use public/private keys.

Nevertheless, I have been tasked with encrypting data using a public key, (specifically, a .CER file). If you ignore the whole symmetric/asymmetric thang, I should just be able to use the key data from the public key as the TripleDES key. However, I'm having difficulty extracting the key bytes from the .CER file. This is the code as it stands..

TripleDESCryptoServiceProvider cryptoProvider = new TripleDESCryptoServiceProvider();
X509Certificate2 cert = new X509Certificate2(@"c:\temp\whatever.cer");
cryptoProvider.Key = cert.PublicKey.Key.

The simplest method I can find to extract the raw key bytes from the certificate is ToXmlString(bool), and then doing some hacky substringing upon the returned string. However, this seems so hackish I feel I must be missing a simpler, more obvious way to do it.

Am I missing a simpler way to use a .cer file to provide the key data to the C# 3DES crypto class, or is hacking it out of the certificate xml string really the best way to go about this?

+2  A: 

cryptoProvider.Key = cert.GetPublicKey()?

jlew
I feel silly now... So obvious!
Gabriel
A: 

I think what you are missing is converting the bytes from the string containing the key-bytes.

Hope the method FromBase64String will help you:

byte[] keyBytes = Convert.FromBase64String(sourceString);
Seb Nilsson
+1  A: 

Encrypting large amounts of data with asymmetric cryptography is not the way to go. Instead, encrypt the data with a symmetric algorithm and encrypt the symmetric key (and IV) with your public key.

This page from MSDN really helped me get going with .Net symmetric cryptography.

Austin Salonen
+4  A: 

It's not a good idea to use keys generated for asymmetric cryptography for symmetric cryptography. There's nothing preventing you from coming up with a way of using a public key as an encryption key for 3DES, but the end result will be that anyone having access to the public key (and this means everyone!) will be able to decrypt your ciphertext.

Alexander
+1  A: 

The real problem here is that the public key is, well, public. Meaning freely available, meaning it's providing zero security of encryption.

Heck, anyone on this thread has all the information they need to decrypt everything. So do googlers.

Please try to encourage your users not to use public key data like that. At the very least, get them to give a password or some other slightly-more-secure chunk you can use to generate a consistent key.

One more thing. Certificate keys vary in size. It can probably handle throwing away extra bytes in the key, but you'll probably get an Array Index / Out Of Bounds exception if the key happens to be shorter than the 3DES key needs. I doubt that'll happen, 3DES only needs 56bits, and cert keys are almost always 256bits or larger.

davenpcj