Asymetric Encryption 5min walk-through

2018-09-14 13_05_12-343286-PAMSX1-119.jpg - Windows Photo Viewer

Cryptography is one of the key-elements in the Blockchain world. We were already looking into the one-way encryption with hash function in the previous post. Encryption of data to be decrypted again, is equally essential and covered by symmetric and asymmetric encryption. I would not attempt to explain the mathematical  and rather complex background of cryptography, but show with some sourcecode how easy it is to integrate such powerful tools in any solution.

Essential for the asymmetric encryption is the creation of a pair of keys, a public and a private key. The public key can be shared with anyone, it is “public”, it can be used by anyone to create an encrypted message (or data) and send it to a receiver which is the only one holding the private key. This private key is the only way to decrypt the message. This provides a very secure communication mechanism. On the contrary there is Symmetric encryption which uses the same key for encryption and decryption.

Anyone who want to deep-dive into cryptography and algorithm I can refer to books and courses. Otherwise we do an express walk-through here in Java, with the shortest possible sample for key generation (5 lines of code) and encryption/decryption (8 lines of code) of text.

Using the Java core packages java.security it is boiling down to a few methods to create a key pair. You have to choose the algorithm (RSA,DSA,DiffieHellman) and initialize with the keysize. It is obviously a crucial design decision where and how to create the keys and distribute it to the right party.

import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
...

private KeyPairGenerator keyGen;
private KeyPair pair;
static PrivateKey privateKey;
static PublicKey publicKey;
...

keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
pair = keyGen.generateKeyPair();
privateKey = pair.getPrivate();
publicKey = pair.getPublic();

To encode and decode a text is similar simple. Take note of the binary format, we have to use Base64 to convert to String and back to binary.

	private String encryptText(String messageText, Key key) {

		Base64.Encoder encoder = Base64.getEncoder();
		try {
			cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return encoder.encodeToString(cipher.doFinal(messageText.getBytes("UTF-8")));

		} catch (Exception e) {
			e.printStackTrace();
			return "nil";
		}
	}

	private String decryptText(String cipherText, Key key) {

		Base64.Decoder decoder = Base64.getDecoder();
		try {
			cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, key);
			return new String(cipher.doFinal(decoder.decode(cipherText)), "UTF-8");

		} catch (Exception e) {
			System.out.println(">>>>>> " + e.getMessage());
			return "nil";
		}
	}

Lets run the sample application, create keys, encode and decode a text.
Take note, attempting to decode with the same key fails and the encoding/decoding works with both keys, you can encode with the public or private key and decode with the respective counterpart. Similar to hash we can see the change of 1 char (“My to MY”) changes the cipher completely.

---- KEY GENERATION ----
Algorithm: RSA
Format: PKCS#8
Private Key:
MIIBVQIB(...obfuscated....)Pk/Vp+iTx64pMSQRiXq7UbXX
Public Key:
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALsDbKCfo55sevpoRL/GjxtlDBFdFLGedfaemCWzh7b/K5ybZbdDrjTVhoyionyGVZuClkZnN5aSRdR6nVXeVL8CAwEAAQ==
------------------------
---- ENCRYPT WITH PUBLIC KEY----
Plain Text: My 2018 Cryptography Sample !
Cipher Text: BkwSG5zczP//7N7AgiFdAyxTvJryPeCLye9zRD1dnKExKR5nABGG3kkiogl8ryujJ+MQB1ISh1EUKSDUm6KYuw==
----------------------------------------------------------
Plain Text: MY 2018 Cryptography Sample !
Cipher Text: Zs8LHPlShaNX/ch8LfrWZrguBJT+WMahMyPQcg06+Nk98i5yd2qyEvP3LfA1QxCmPdFQEPoS7nQxvnPVxE7s0g==
----------------------------------------------------------
---- DECRYPT WITH PRIVATE KEY----
Cipher Text: Zs8LHPlShaNX/ch8LfrWZrguBJT+WMahMyPQcg06+Nk98i5yd2qyEvP3LfA1QxCmPdFQEPoS7nQxvnPVxE7s0g==
Plain Text: MY 2018 Cryptography Sample !
------------------------
---- DECRYPT WITH PUBLIC KEY----
>>>>>> Decryption error
Cipher Text: Zs8LHPlShaNX/ch8LfrWZrguBJT+WMahMyPQcg06+Nk98i5yd2qyEvP3LfA1QxCmPdFQEPoS7nQxvnPVxE7s0g==
Plain Text: nil
----------------------------------------------------------
---- ENCRYPT WITH PRIVATE KEY----
Plain Text: My 2018 Cryptography Sample !
Cipher Text: sjm/MwtAy/MwThhRVKa8lJ0ro1PTHXSK5QfRNLHnYb7X/ezSCLTRPCU7z5TZg7S5ptR2Tvkj4P1J/fk8CNY6xA==
----------------------------------------------------------
---- DECRYPT WITH PUBLIC KEY----
Cipher Text: sjm/MwtAy/MwThhRVKa8lJ0ro1PTHXSK5QfRNLHnYb7X/ezSCLTRPCU7z5TZg7S5ptR2Tvkj4P1J/fk8CNY6xA==
Plain Text: My 2018 Cryptography Sample !

The complete sample sourcecode here on github.
Stay tuned.

Disclaimer: This discussion, datamodel and sourcecode or application is for study purpose solely. It does not reflect or replicate any existing commercial product. It is also not fit for or meant for production.

Leave a comment