Java - RSA Encryption and Decryption example - Asymmetric cryptography

The RSA algorithm (Rivest-Shamir-Adleman) is a cryptographic algorithm that is used for specific security services or purposes, which enables public-key encryption and is widely used to secure sensitive data, particularly when it is being sent over an insecure network such as the HTTP. A public key is shared publicly, while a private key is secret and must not be shared with anyone.

The following illustration highlights how asymmetric cryptography works:


Example 1:

The Cipher Type: RSA/ECB/PKCS1Padding

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;

/*
* RSA Key Size: 1024
* Cipher Type: RSA/ECB/PKCS1Padding
*/
public class RSAExample1 {
public PrivateKey privateKey;
public PublicKey publicKey;

public RSAExample1() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair pair = keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
}

public PrivateKey getPrivateKey() {
return privateKey;
}

public PublicKey getPublicKey() {
return publicKey;
}

// convert String publickey to Key object
public static Key loadPublicKey(String stored)
throws GeneralSecurityException, IOException {
byte[] data = Base64.getDecoder().decode((stored.getBytes()));
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}

// Encrypt using public key
public static String encryptMessage(String plainText, String publickey)
throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publickey));
return Base64.getEncoder().
encodeToString(cipher.doFinal(plainText.getBytes()));
}

// Decrypt using private key
public static String decryptMessage(String encryptedText,
String privatekey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, loadPrivateKey(privatekey));
return new String(cipher.
doFinal(Base64.getDecoder().decode(encryptedText)));
}

// Convert String private key to privateKey object
public static PrivateKey loadPrivateKey(String key64)
throws GeneralSecurityException {
byte[] clear = Base64.getDecoder().decode((key64.getBytes()));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);
Arrays.fill(clear, (byte) 0);
return priv;
}

public static void main(String[] args) throws Exception {
final String secretText = "www.knowledgefactory.net";
RSAExample1 keyPairGenerator = new RSAExample1();
// Generate private and public key
String privateKey = Base64.getEncoder().
encodeToString(keyPairGenerator.getPrivateKey().getEncoded());
String publicKey = Base64.getEncoder().
encodeToString(keyPairGenerator.getPublicKey().getEncoded());
System.out.println("Private Key: " + privateKey);
System.out.println("Public Key: " + publicKey);

// Encrypt secret text using public key
String encryptedValue = RSAExample1.
encryptMessage(secretText, publicKey);
System.out.println("Encrypted Value: " + encryptedValue);
// Decrypt
String decryptedText = RSAExample1.
decryptMessage(encryptedValue, privateKey);
System.out.println("Decrypted output: " + decryptedText);
}
}

Output:

Private Key:

MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIJx7CewN3OqaW0xyX2GtZ0kXdnltwY6zgDim9Cx01yC814s/tOYzizMolmKAq60sAjeFJ64+/GMjgZ6OwOOF65simQv/Nw20JNfrJfStGKNcqB5aHYEzfpSTrMlIBSHJWTqKgJN8IKdJaDimOe7deAoumdZasJMtnuloiMNqFuXAgMBAAECgYBUk4DGit6pRAhvICTAGqOOa5HeQa7VfzMqJ8NXILUl+lHI8euXTi//o/5vh6gNlmG8niFIeDACgVtkn8O7nlmDdR4EXckwsjsSStomhWQCdW70fgPsxEOQeWwIx8eq7nQkskDXXINYe9XZLhIeKRFErWmXUVqoac1PUXFz9z0eYQJBALrKlVTAcbv+HM4RetWkTtCKOkW6MH2ZvDbCF2pm0gc9EaPbU29DT8+UUUW5HaHfFEU7vc49xo9Eew5aAJf4YIsCQQCyxs/ST2QGWs9orwjYRePq4Sh0jUOG3VzNqMpchPMImcTQJHPYFNEQVLiJ79Z3rHNbr2jSLrtep6nLjA9q6KalAkBMX4BnQrg+EUxdxS/gImpHQf1JfTNOZ4lZKkrAqoG9i+6mfIrEt1TunsoMJABFqxxyolac+Q0yjuFxoMMVX+y5AkBYJJ2iW3I9j9hjDKmXuB2/WHPRwzRf8hQncekT5JjOzMG0vcQ/7UOGgb7ag12Cc4wM0FcmCdRnvtKAgPW5CCvhAkBAgTCZC2lXL2D3YDX+IKRRXy25VMxYgJVyy6EvylzOYr/9Hr4W8ZCWNCBo7BYKqerQw1Mr7+QwROMB28uOsUxJ

Public Key:

MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCcewnsDdzqmltMcl9hrWdJF3Z5bcGOs4A4pvQsdNcgvNeLP7TmM4szKJZigKutLAI3hSeuPvxjI4GejsDjheubIpkL/zcNtCTX6yX0rRijXKgeWh2BM36Uk6zJSAUhyVk6ioCTfCCnSWg4pjnu3XgKLpnWWrCTLZ7paIjDahblwIDAQAB

Encrypted Value:

ZPALqib8TJDVl2GEJeqg9VgITROWTpn4XnFhu0VK7sCDFR6JzblyTo6oQ7nTtBkQEmaCeoFoJKTyIxTj0xPoDMBZB4n8RHQf8ZDaPbaE5ipKUhmGuOhpXiXlOZw7O2hDP8qfpDLE6Z7R5R0MQ9r2G27beQ1pKEmq4iPU7DGo9tQ=

Decrypted output: www.knowledgefactory.net



Example 2:

The Cipher Type: RSA/ECB/OAEPWithSHA-1AndMGF1Padding

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;

/*
* RSA Key Size: 2048
* Cipher Type: RSA/ECB/OAEPWithSHA-1AndMGF1Padding
*/
public class RSAExample2 {
public PrivateKey privateKey;
public PublicKey publicKey;

public RSAExample2() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair pair = keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
}

public PrivateKey getPrivateKey() {
return privateKey;
}

public PublicKey getPublicKey() {
return publicKey;
}

// convert String publickey to Key object
public static Key loadPublicKey(String stored)
throws GeneralSecurityException, IOException {
byte[] data = Base64.getDecoder().decode((stored.getBytes()));
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}

// Encrypt using publickey
public static String encryptMessage(String plainText, String publickey)
throws Exception {
Cipher cipher = Cipher.
getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publickey));
return Base64.getEncoder().
encodeToString(cipher.doFinal(plainText.getBytes()));
}

// Decrypt using privatekey
public static String decryptMessage(String encryptedText,
String privatekey) throws Exception {
Cipher cipher = Cipher.
getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, loadPrivateKey(privatekey));
return new String(cipher.
doFinal(Base64.getDecoder().decode(encryptedText)));
}

// Convert String private key to privateKey object
public static PrivateKey loadPrivateKey(String key64)
throws GeneralSecurityException {
byte[] clear = Base64.getDecoder().decode((key64.getBytes()));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);
Arrays.fill(clear, (byte) 0);
return priv;
}

public static void main(String[] args) throws Exception {
final String secretText = "www.knowledgefactory.net";
RSAExample2 keyPairGenerator = new RSAExample2();
// Generate private and public key
String privateKey = Base64.getEncoder().
encodeToString(keyPairGenerator.getPrivateKey().getEncoded());
String publicKey = Base64.getEncoder().
encodeToString(keyPairGenerator.getPublicKey().getEncoded());
System.out.println("Private Key: " + privateKey);
System.out.println("Public Key: " + publicKey);

// Encrypt secret text using public key
String encryptedValue = RSAExample2.
encryptMessage(secretText, publicKey);
System.out.println("Encrypted Value: " + encryptedValue);
// Decrypt
String decryptedText = RSAExample2.
decryptMessage(encryptedValue, privateKey);
System.out.println("Decrypted output: " + decryptedText);
}
}



Example 3:

The Cipher Type: RSA/ECB/OAEPWithSHA-256AndMGF1Padding 

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;

/*
* RSA Key Size: 4096
* Cipher Type: RSA/ECB/OAEPWithSHA-256AndMGF1Padding
*/
public class RSAExample3 {
public PrivateKey privateKey;
public PublicKey publicKey;

public RSAExample3() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(4096);
KeyPair pair = keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
}

public PrivateKey getPrivateKey() {
return privateKey;
}

public PublicKey getPublicKey() {
return publicKey;
}

// convert String publickey to Key object
public static Key loadPublicKey(String stored)
throws GeneralSecurityException, IOException {
byte[] data = Base64.getDecoder().decode((stored.getBytes()));
X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
KeyFactory fact = KeyFactory.getInstance("RSA");
return fact.generatePublic(spec);
}

// Encrypt using publickey
public static String encryptMessage(String plainText, String publickey)
throws Exception {
Cipher cipher = Cipher.
getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, loadPublicKey(publickey));
return Base64.getEncoder().
encodeToString(cipher.doFinal(plainText.getBytes()));
}

// Decrypt using privatekey
public static String decryptMessage(String encryptedText,
String privatekey) throws Exception {
Cipher cipher = Cipher.
getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, loadPrivateKey(privatekey));
return new String(cipher.
doFinal(Base64.getDecoder().decode(encryptedText)));
}

// Convert String private key to privateKey object
public static PrivateKey loadPrivateKey(String key64)
throws GeneralSecurityException {
byte[] clear = Base64.getDecoder().decode((key64.getBytes()));
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priv = fact.generatePrivate(keySpec);
Arrays.fill(clear, (byte) 0);
return priv;
}

public static void main(String[] args) throws Exception {
final String secretText = "www.knowledgefactory.net";
RSAExample3 keyPairGenerator = new RSAExample3();
// Generate private and public key
String privateKey = Base64.getEncoder().
encodeToString(keyPairGenerator.getPrivateKey().getEncoded());
String publicKey = Base64.getEncoder().
encodeToString(keyPairGenerator.getPublicKey().getEncoded());
System.out.println("Private Key: " + privateKey);
System.out.println("Public Key: " + publicKey);

// Encrypt secret text using public key
String encryptedValue = RSAExample3.
encryptMessage(secretText, publicKey);
System.out.println("Encrypted Value: " + encryptedValue);
// Decrypt
String decryptedText = RSAExample3.
decryptMessage(encryptedValue, privateKey);
System.out.println("Decrypted output: " + decryptedText);
}
}

More...

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete