Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of RSA generation, sign, verify, encryption, decryption and keystores in Java
import javax.crypto.Cipher;
import java.util.Base64;
import static java.nio.charset.StandardCharsets.UTF_8;
public class RsaExample {
public static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, new SecureRandom());
KeyPair pair = generator.generateKeyPair();
return pair;
public static KeyPair getKeyPairFromKeyStore() throws Exception {
//Generated with:
// keytool -genkeypair -alias mykey -storepass s3cr3t -keypass s3cr3t -keyalg RSA -keystore keystore.jks
InputStream ins = RsaExample.class.getResourceAsStream("/keystore.jks");
KeyStore keyStore = KeyStore.getInstance("JCEKS");
keyStore.load(ins, "s3cr3t".toCharArray()); //Keystore password
KeyStore.PasswordProtection keyPassword = //Key password
new KeyStore.PasswordProtection("s3cr3t".toCharArray());
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry("mykey", keyPassword); cert = keyStore.getCertificate("mykey");
PublicKey publicKey = cert.getPublicKey();
PrivateKey privateKey = privateKeyEntry.getPrivateKey();
return new KeyPair(publicKey, privateKey);
public static String encrypt(String plainText, PublicKey publicKey) throws Exception {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(UTF_8));
return Base64.getEncoder().encodeToString(cipherText);
public static String decrypt(String cipherText, PrivateKey privateKey) throws Exception {
byte[] bytes = Base64.getDecoder().decode(cipherText);
Cipher decriptCipher = Cipher.getInstance("RSA");
decriptCipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(decriptCipher.doFinal(bytes), UTF_8);
public static String sign(String plainText, PrivateKey privateKey) throws Exception {
Signature privateSignature = Signature.getInstance("SHA256withRSA");
byte[] signature = privateSignature.sign();
return Base64.getEncoder().encodeToString(signature);
public static boolean verify(String plainText, String signature, PublicKey publicKey) throws Exception {
Signature publicSignature = Signature.getInstance("SHA256withRSA");
byte[] signatureBytes = Base64.getDecoder().decode(signature);
return publicSignature.verify(signatureBytes);
public static void main(String... argv) throws Exception {
//First generate a public/private key pair
KeyPair pair = generateKeyPair();
//KeyPair pair = getKeyPairFromKeyStore();
//Our secret message
String message = "the answer to life the universe and everything";
//Encrypt the message
String cipherText = encrypt(message, pair.getPublic());
//Now decrypt it
String decipheredMessage = decrypt(cipherText, pair.getPrivate());
//Let's sign our message
String signature = sign("foobar", pair.getPrivate());
//Let's check the signature
boolean isCorrect = verify("foobar", signature, pair.getPublic());
System.out.println("Signature correct: " + isCorrect);
Copy link

abdabughazaleh commented Oct 17, 2019

It's good thank you so much , How can i create base64 like jwt (header,body,sign) ?

Copy link

stdunbar commented Nov 26, 2019

Thanks for the code. One issue - using openjdk version "11.0.5-ea" 2019-10-15 requires the KeyStore.getInstance("JCEKS") code to be KeyStore.getInstance("PKCS12").

Copy link

sopanlavhale commented Dec 29, 2019

@stdunbar: It depends on your keyStore creation.

Copy link

bhaveshf-cuelogic commented Jun 14, 2020

Linking back to OP for reference :

Copy link

difafebri commented Jan 5, 2021

thank you so much for this and your article.. it helped me understand a bit more abt how RSA works

Copy link

Simon-Str commented Jan 17, 2021

Thank you so much! I needed that for my uni project and you were the only one loading it from a Keystore :)

Copy link

acuna-public commented Apr 3, 2021

Thank you, but what is generateKeyPair(), does it using for test purposes for not to use the Kestore?

Copy link

jokanovicc commented May 28, 2021

Intellij can't find .jks file-gives Null but in Eclipse it works well.
Any idea or solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment