{{announcement.body}}
{{announcement.title}}

# Encryption, Part 2: Public Key/Private Key Encryption

DZone 's Guide to

# Encryption, Part 2: Public Key/Private Key Encryption

· Security Zone ·
Free Resource

Comment (4)

Save
{{ articles[0].views | formatCount}} Views

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.Cipher;
import javax.crypto.IllegalBlockSizeException;

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();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
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();
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
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!

Topics:
encryption, java, keys, private key, public key, security, symmetric encryption

Comment (4)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.