Pergunta

My code looks like this, I traced each undefined method here to the functions called with relevant arguments included.

I have a hard time wrapping my head around the API. So what I have here is that I can generate public/private keys, and I can generate a session key, but how can I generate a session key based on the public key? What am I missing/assuming (wrong) here?



void Crypto::GenerateKeyPair( Buffer& publicKey, Buffer& privateKey ) throw(WinError)
{
    /* CryptAcquireContext ( PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) */
    CryptContext context = CryptoProviders::NewContext(PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    /* CryptGenKey( AT_KEYEXCHANGE, CRYPT_EXPORTABLE, &key) */
    CryptKey key = context.GenerateKeyExchangePair(); 
    /* CryptExportKey( PUBLICKEYBLOB, pPub); */
    key.ExportPublicKey(publicKey);
    /* CryptExportKey( PRIVATEKEYBLOB, pPriv); */
    key.ExportPrivateKey(privateKey);
}


void Crypto::GenerateSessionKey( Buffer& sessionKey ) throw(WinError)
{
    /* CryptAcquireContext ( PROV_RSA_FULL, 0 ) */
    CryptContext context = CryptoProviders::NewContext(PROV_RSA_FULL, 0);
    /* CryptGenKey( CALG_RC4, CRYPT_EXPORTABLE ) */
    /* CryptGetUserKey( AT_KEYEXCHANGE ) */
    /* CryptExportKey( SIMPLEBLOB ) */
    context.GenerateSessionKey(sessionKey);
}

void Crypto::EncryptData( const Buffer& publicKey, const Buffer& plaintext, Buffer& encrypted )
{
    /* CryptAcquireContext ( PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) */
    CryptContext hProvider(PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    /* CryptImportKey( 0 ) */
    CryptKey key = hProvider.ImportKey(publicKey);
    /* CryptEncrypt() */
    key.Encrypt(plaintext, encrypted);

}

void Crypto::DecryptData( const Buffer& privateKey, const Buffer& encrypted, Buffer& plaintext )
{
    /* CryptAcquireContext ( PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) */
    CryptContext hProvider(PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
    /* CryptImportKey( 0 ) */
    CryptKey key = hProvider.ImportKey(privateKey);
    /* CryptDecrypt() */
    key.Decrypt(encrypted, plaintext);
}
Foi útil?

Solução

Session key is a symmetric key (meaning same key used for encryption and decryption). It is EXCHANGED with the other node secretly using asymmetric key pair (public and private keys).

So you do not generate session key from public key, rather you come up with a session key on your own (or better yet negotiate through some protocol as pointed out in comment e.g. D-H key exchange) and encrypt that using the other node's public key and send. So only the other side can discover the session key because ONLY it can decrypt data using its private key.

Reading reasons for using session keys would help

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top