DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Encryption, Part 2: Public Key/Private Key Encryption

Encryption, Part 2: Public Key/Private Key Encryption

Learn more about encryption, specifically public and private keys.

Bipin Patwardhan user avatar by
Bipin Patwardhan
·
Apr. 26, 19 · Presentation
Like (11)
Save
Tweet
Share
35.73K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous article, I presented the concept of symmetric encryption, where the same key is used to encrypt and decrypt data. The biggest limitation of symmetric encryption is the key itself. The key used for encryption and decryption has to be kept a secret. If the key is compromised, the encrypted data is no longer secure. While you may feel that it will be easy to keep the key safe, consider the fact that the same key cannot be used to encrypt data between multiple parties. For example, if Alice and Bob agree to use a secret key X for exchanging their messages, the same key X cannot be used to exchange messages between Alice and Jane. This is because such messages can be decrypted by Bob as well. Hence, in addition to keeping the key a secret, each pair that wishes to communicate secretly will have to maintain a key for their conversation.

This problem is overcome by the concept of public key/private key encryption (also known as Public Key Encryption or PKE for short).

In the PKE method, two keys are used in the encryption-decryption process. One key is used for encryption, while the other key is used for decryption. As the same key is not used for encryption and decryption, this technique is also known as 'asymmetric encryption'.

In the PKE method, when Alice and Bob wish to exchange messages, both will generate two keys — a private key and a public key. As the names suggest, the private key is not disclosed, while the public key is shared with everyone. When Bob wishes to send a message to Alice, he uses Alice's public key to encrypt the message and send the encrypted message to Alice. On getting the message, Alice decrypts the message using her private key, to get the original message.

The best part of the PKE method is that the public key can be used by anyone to send a message, which can then be decrypted using the private key. As long as the private key is not compromised, the encrypted message cannot be decrypted easily, if at all.

Java code to illustrate the PKE method is given below

package edpkpk;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class EncDecPublicKeyPrivateKey
{
// key encryption algorithms supported - RSA, Diffie-Hellman, DSA
// key pair generator - RSA: keyword - RSA, key size: 1024, 2048
// key pair generator - Diffie-Hellman: keyword i DiffieHellman, key size - 1024
// key pair generator - DSA: keyword - DSA, key size: 1024
// NOTE: using asymmetric algorithms other than RSA needs to be worked out 
protected static String DEFAULT_ENCRYPTION_ALGORITHM = "RSA";
protected static int DEFAULT_ENCRYPTION_KEY_LENGTH = 1024;
protected static String DEFAULT_TRANSFORMATION = "RSA/ECB/PKCS1Padding";

protected String mEncryptionAlgorithm, mTransformation;
protected int mEncryptionKeyLength;
protected PublicKey mPublicKey;
protected PrivateKey mPrivateKey;

EncDecPublicKeyPrivateKey()
{
mEncryptionAlgorithm = EncDecPublicKeyPrivateKey.DEFAULT_ENCRYPTION_ALGORITHM;
mEncryptionKeyLength = EncDecPublicKeyPrivateKey.DEFAULT_ENCRYPTION_KEY_LENGTH;
mTransformation = EncDecPublicKeyPrivateKey.DEFAULT_TRANSFORMATION;
mPublicKey = null;
mPrivateKey = null;
}

public static BigInteger keyToNumber(byte[] byteArray)
{
return new BigInteger(1, byteArray);
}

public String getEncryptionAlgorithm()
{
return mEncryptionAlgorithm;
}

public int getEncryptionKeyLength()
{
return mEncryptionKeyLength;
}

public String getTransformation()
{
return mTransformation;
}

public PublicKey getPublicKey()
{
return mPublicKey;
}

public byte[] getPublicKeyAsByteArray()
{
return mPublicKey.getEncoded();
}

public String getEncodedPublicKey()
{
String encodedKey = Base64.getEncoder().encodeToString(mPublicKey.getEncoded());
return encodedKey;
}

public PrivateKey getPrivateKey()
{
return mPrivateKey;
}

public byte[] getPrivateKeyAsByteArray()
{
return mPrivateKey.getEncoded();
}

public String getEncodedPrivateKey()
{
String encodedKey = Base64.getEncoder().encodeToString(mPrivateKey.getEncoded());
return encodedKey;
}

public byte[] encryptText(String text)
{
byte[] encryptedText = null;
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(mEncryptionAlgorithm);
kpg.initialize(mEncryptionKeyLength);

KeyPair keyPair = kpg.generateKeyPair();

mPublicKey = keyPair.getPublic();
mPrivateKey = keyPair.getPrivate();

Cipher cipher = Cipher.getInstance(mTransformation);
cipher.init(Cipher.PUBLIC_KEY, mPublicKey);

encryptedText = cipher.doFinal(text.getBytes());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}

return encryptedText;
}

public byte[] decryptText(byte[] encryptedText)
{
byte[] decryptedText = null;

try {
Cipher cipher = Cipher.getInstance(mTransformation);
cipher.init(Cipher.PRIVATE_KEY, mPrivateKey);

decryptedText = cipher.doFinal(encryptedText);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}

return decryptedText;
}
}


And the main block to call this code will look like:

package edpkpk;

public class Main
{
public static void encryptDecrypt(String plainText)
{
EncDecPublicKeyPrivateKey edpkpk = new EncDecPublicKeyPrivateKey();

//byte[] secretKeyByteArray = sed.getSecretKeyAsByteArray();
//System.out.println("secret key: '" + EncryptDecryptPublicKeyPrivateKey.keyToNumber(secretKeyByteArray).toString() + "'" );

System.out.println("plainText: '" + plainText + "'");
System.out.println("plainText size: '" + plainText.length() + "'");

System.out.println("encryption key length: '" + edpkpk.getEncryptionKeyLength() + "'");
System.out.println("encryption algorithm: '" + edpkpk.getEncryptionAlgorithm() + "'");
System.out.println("encryption transform: '" + edpkpk.getTransformation() + "'");

byte[] encryptedText = edpkpk.encryptText(plainText);
System.out.println("encrypted text: '" + EncDecPublicKeyPrivateKey.keyToNumber(encryptedText).toString() + "'" );
System.out.println("encrypted text length: '" + EncDecPublicKeyPrivateKey.keyToNumber(encryptedText).toString().length() + "'" );

System.out.println("public key: '" + EncDecPublicKeyPrivateKey.keyToNumber(edpkpk.getPublicKeyAsByteArray()).toString() + "'" );
System.out.println("public key length: '" + EncDecPublicKeyPrivateKey.keyToNumber(edpkpk.getPublicKeyAsByteArray()).toString().length() + "'" );
System.out.println("private key: '" + EncDecPublicKeyPrivateKey.keyToNumber(edpkpk.getPrivateKeyAsByteArray()).toString() + "'" );
System.out.println("private key length: '" + EncDecPublicKeyPrivateKey.keyToNumber(edpkpk.getPrivateKeyAsByteArray()).toString().length() + "'" );

String decryptedText = new String(edpkpk.decryptText(encryptedText));
System.out.println("decrypted text: '" + decryptedText + "'" );
System.out.println("decrypted text length: '" + decryptedText.length() + "'");
}

public static void main(String[] args)
{
String plainText1 = "Hello World, Public Key / Private Key style";
Main.encryptDecrypt(plainText1);
//System.out.println("----------------------------------------------------------------");
//String plainText2 = "Hello World, Public Key / Private Key style with a very loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooog piece of text";
//Main.encryptDecrypt(plainText2);
}
}


While the PKE method is secure and more robust than symmetric encryption, it has a few limitations. One of the limitations is the method is slower than symmetric encryption. The second limitation is that the message has to be encrypted in blocks, with the length of each block being smaller than the length of the key. For example, if the RSA algorithm, with a key length of 1024 is used, the maximum length of the block that can be encrypted is around 117 characters [length of block = (key length / 64 ) - 11 ].

In the next article, I will cover the hybrid method of encryption.

Stay tuned!

Alice (software) Blocks Concept (generic programming) Data (computing) security Java (programming language) Conversations (software) Algorithm Jane (software)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Old School or Still Cool? Top Reasons To Choose ETL Over ELT
  • 10 Most Popular Frameworks for Building RESTful APIs
  • How To Perform Local Website Testing Using Selenium And Java
  • A Beginner’s Guide To Styling CSS Forms

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: