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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • SIEM Volume Spike Alerts Using ML
  • Doubly Linked List in Data Structures and Algorithms
  • DZone Community Awards 2022
  • What Is Encryption and How Does It Work?

Trending

  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Simpler Data Transfer Objects With Java Records
  • Assessing Bias in AI Chatbot Responses
  • Mastering Deployment Strategies: Navigating the Path to Seamless Software Releases
  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.

By 
Bipin Patwardhan user avatar
Bipin Patwardhan
·
Apr. 26, 19 · Presentation
Likes (11)
Comment
Save
Tweet
Share
37.7K 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.

Related

  • SIEM Volume Spike Alerts Using ML
  • Doubly Linked List in Data Structures and Algorithms
  • DZone Community Awards 2022
  • What Is Encryption and How Does It Work?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!