Asymmetric (public key) encryption in Java

Asymmetric encryption, also referred to as public key encryption, is a method for communicating securely between different parties without them having to disclose a single secret key over an insecure channel. Asymmetric encryption generally works as follows:

  • Alice wants to send a secure message to Bob. So Bob generates a key pair, consisting of a private key, which Bob keeps secret, plus a corresponding public key, which Bob can freely disclose to Alice (or any other party).
  • Alice encrypts her message using Bob's public key and sends it to Bob.
  • Bob decrypts the message using his private key, which is required in order to decrypt it. Since Bob never disclosed his private key, and this is required to decrypt the message, the communiction is secure in principle.

One solution to this problem is via an asymmetric encryption algorithm. In asymmetric encryption, also known as public key encryption or public key cryptography:

With additional infrastructure, some asymmetric encryption schemes can also be used to help address the last of these points, i.e. party authentication.

Asymmetric encryption for key exchanges

As mentioned above, asymmetric encryption schemes are generally computationally expensive. In most use cases, the "message" that is sent with asymmetric encryption is another encryption key: this time, a key to a more efficient symmetric encryption scheme that will then be used to continue the communication. This system is used as a key exchange and because it is a common use case, Java includes the KeyAgreement class to simplify the process, along with calls to "wrap" and "unwrap" a key from a Cipher object.

A common asymmetric encryption scheme: RSA

One of the most commonly used asymmetric encryption schemes in practice is RSA encryption. You can perform RSA encryption in Java by creating a Cipher with the RSA scheme.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.