As for keeping the key secret from all but your intended recipient, well, some of the well-known algorithms need two keys - and a message encrypted with one of the keys can only be decrypted with the other. So once you and your intended recipient have agreed which algorithm to use, your recipient's software generates a pair of keys, and sends you one (called his/her public key) while keeping the other one secret, even from you (this one is called his/her private key). Your software then encrypts and sends your message using the public key, and the recipient's software decrypts it using the private key.
So there's no danger of the private key being discovered by an eavesdropper - it never gets sent anywhere. It is known only to its owner.
As for the public key, there's no need to keep it secret. On the contrary, it can safely be made available to anyone who requests it. We'll come back later to how this is done.
An algorithm like this, using a private key and a public key, is called asymmetric. An algorithm that uses just one key, which has to be a secret between the sender and recipient, is called symmetric, and the key is called a secret key.
An algorithm that uses a private key and a public key is also called a public key algorithm. One of the best known ones is RSA, developed by Ron Rivest, Adi Shamir, and Leonard Adleman in 1977. An algorithm that uses just one key, a secret key, is called a secret key algorithm. One of the best known ones is Data Encryption Standard (DES), published as a US standard in 1977.