Encrypt using RSA cryptography in Java

This is an example of Java implementation of encryption with RSA encryption. Two patterns are implemented: encryption with private key → decryption with public key, encryption with public key → decryption with private key.

import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;

public class Main {
	public static void main(String[] args) throws Exception {
		//Generate public / private key.
		KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");
		kg.initialize(1024);
		KeyPair keyPair = kg.generateKeyPair();
		KeyFactory factoty = KeyFactory.getInstance("RSA");
		RSAPublicKeySpec publicKeySpec = factoty.getKeySpec(keyPair.getPublic(), RSAPublicKeySpec.class);
		RSAPrivateKeySpec privateKeySpec = factoty.getKeySpec(keyPair.getPrivate(), RSAPrivateKeySpec.class);
		PublicKey publicKey = factoty.generatePublic(publicKeySpec);
		PrivateKey privateKey = factoty.generatePrivate(privateKeySpec);

        //Plaintext
		byte[] plain = new byte[] { 0x01, 0x02 };

        //Encrypt with private key and decrypt with public key.
		Cipher encrypterWithPrivateKey = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		encrypterWithPrivateKey.init(Cipher.ENCRYPT_MODE, privateKey);
		byte[] encryptedWithPrivateKey = encrypterWithPrivateKey.doFinal(plain);
	    System.out.println("encryptedWithPrivateKey (" + encryptedWithPrivateKey.length + " bytes):");
		System.out.println(decodeHex(encryptedWithPrivateKey));

		Cipher decrypterWithPublicKey = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		decrypterWithPublicKey.init(Cipher.DECRYPT_MODE, publicKey);
		byte[] decryptedWithPrivateKey = decrypterWithPublicKey.doFinal(encryptedWithPrivateKey);
	    System.out.println("decryptedWithPrivateKey (" + decryptedWithPrivateKey.length + " bytes):");
		System.out.println(decodeHex(decryptedWithPrivateKey));

		//Encrypt with public key and decrypt with private key.
		Cipher encrypterWithPublicKey = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		encrypterWithPublicKey.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] encryptedWithPublicKey = encrypterWithPublicKey.doFinal(plain);
	    System.out.println("encryptedWithPublicKey (" + encryptedWithPublicKey.length + " bytes):");
		System.out.println(decodeHex(encryptedWithPublicKey));
		
		Cipher decrypterWithPriavteKey = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		decrypterWithPriavteKey.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] decryptedWithPriavteKey = decrypterWithPriavteKey.doFinal(encryptedWithPublicKey);
	    System.out.println("decryptedWithPriavteKey (" + decryptedWithPriavteKey.length + " bytes):");
		System.out.println(decodeHex(decryptedWithPriavteKey));
	}

	/**Convert the byte array to hexadecimal notation.*/
	public static String decodeHex(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (byte b : bytes) {
			sb.append(String.format("%02x", b));
		}
        return sb.toString();
	}
}

Execute with paiza.io.

Recommended Posts

Encrypt using RSA cryptography in Java
Try using RocksDB in Java
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
How to encrypt and decrypt with RSA public key in Java
Try using the Stream API in Java
Using JavaScript from Java in Rhino 2021 version
[Java] Use cryptography in the standard library
ERRORCODE = -4471 occurs in Java application using Db2.
Try using JSON format API in Java
Read Felica using RC-S380 (PaSoRi) in Java
Changes in Java 11
Rock-paper-scissors in Java
Pi in Java
FizzBuzz in Java
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
Send email using Amazon SES SMTP in Java
Send push notifications using Notification Hubs in Java
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Try using Sourcetrail (macOS version) in Java code
Match IP addresses using regular expressions in Java
Display "Hello World" in the browser using Java
Display "Hello World" in the browser using Java
Try using the COTOHA API parsing in Java
NLP4J [001b] Morphological analysis in Java (using kuromoji)
Encrypt / decrypt with AES256 in PHP and Java
[java] sort in list
Read JSON in Java
Sorting using java comparator
Make Blackjack in Java
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
I tried using Google Cloud Vision API in Java
Comments in Java source
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Scraping practice using Java ②
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Scraping practice using Java ①
How to convert A to a and a to A using AND and OR in Java
Express failure in Java
I tried using an extended for statement in Java