15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

556 ❘ ChaPTer 21 security<br />

}<br />

byte[] signature = signingAlg.SignData(data);<br />

signingAlg.Clear();<br />

return signature;<br />

For verification if the signature was really from Alice, Bob checks the signature by using the public key from<br />

Alice. The byte array containing the public key blob can be imported to a CngKey object with the static<br />

Import() method. The ECDsaCng class is then used to verify the signature by invoking VerifyData().<br />

}<br />

}<br />

static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey)<br />

{<br />

bool retValue = false;<br />

using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))<br />

{<br />

var signingAlg = new ECDsaCng(key);<br />

retValue = signingAlg.VerifyData(data, signature);<br />

signingAlg.Clear();<br />

}<br />

return retValue;<br />

}<br />

Key exchange <strong>and</strong> secure Transfer<br />

Let’s get into a more complex example to exchange a symmetric key for a secure transfer by using the Diffie<br />

Hellman algorithm. In the Main() method, you can see the main functionality. Alice creates an encrypted<br />

message <strong>and</strong> sends the encrypted message to Bob. Before that, key pairs are created for Alice <strong>and</strong> Bob.<br />

Bob gets access only to Alice’s public key, <strong>and</strong> Alice gets access only to Bob’s public key.<br />

using System;<br />

using System.IO;<br />

using System.Security.Cryptography;<br />

using System.Text;<br />

namespace Wrox.ProCSharp.Security<br />

{<br />

class Program<br />

{<br />

static CngKey aliceKey;<br />

static CngKey bobKey;<br />

static byte[] alicePubKeyBlob;<br />

static byte[] bobPubKeyBlob;<br />

static void Main()<br />

{<br />

CreateKeys();<br />

byte[] encrytpedData = AliceSendsData("secret message");<br />

BobReceivesData(encrytpedData);<br />

}<br />

code snippet SecureTransfer/Program.cs<br />

In the implementation of the CreateKeys() method, keys are created to be used with the EC Diffie Hellman<br />

256 algorithm.<br />

private static void CreateKeys()<br />

{<br />

aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);<br />

bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256);<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!