Exchanging Session Keys

To send another user an encrypted message, the sender must send the receiver the session key used to perform the encryption. There are two ways of doing this:

    To send an encrypted session key

  1. Create a random session key, using the CryptGenKey function.
  2. Encode the message, using the session key.

    For more information on encoding a message using a session key, see Encrypting and Decrypting Data.

  3. Export the session key into a key BLOB with the CryptExportKey function.

    Specify that the key be encoded with the destination user's key exchange public key, which is the receiver's public key.

  4. Send the encoded message and the encoded key BLOB to the destination user.
  5. The receiver then imports the key BLOB into the CSP, using the CryptImportKey function.

    This automatically decodes the session key, provided that the destination user's key exchange private key was specified in step three.

  6. The receiver can then decode the message, using the session key, following the procedure discussed in Encrypting and Decrypting Data.

The following illustration shows how to send an encoded message, using this procedure.

This approach is vulnerable in at least one way. A hacker can acquire copies of one of more encrypted messages and the encoded keys. Then, at some later time, the hacker can send one of these messages to the receiver and the receiver has no way of knowing that the message did not come directly from the original sender. This risk can be reduced by timestamping all messages or by using serial numbers. Timestamping involves attaching the date and time to each message. Using a three-phase key exchange protocol eliminates this problem entirely. For more information on using this protocol, see the Microsoft Platform SDK.