Master RSA Asymmetric Encryption in Java: From Keytool to Code

This guide walks you through generating an RSA keystore, exporting a public‑key certificate, and implementing full asymmetric encryption and decryption in Java, illustrating each step with command‑line examples, code snippets, and expected outputs.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master RSA Asymmetric Encryption in Java: From Keytool to Code

For an introduction to asymmetric encryption, see the referenced article on RSA.

1. Generate a keystore

keytool -genkeypair -keysize 2048 -keyalg RSA -alias test -dname "cn=test,ou=test,o=test,l=wlmq,st=xj,c=tk" -keypass 123123 -storepass 123123 -keystore test.keystore

The command creates test.keystore using RSA with a 2048‑bit key; both the keystore password and private‑key password are 123123.

View keystore details

keytool -list -storepass 123123 -keystore test.keystore

The output shows one certificate with alias test.

2. Export the certificate

keytool -exportcert -alias test -storepass 123123 -keystore test.keystore -file test.cer -v

The generated test.cer contains only the public key, suitable for encryption and signature verification.

View certificate content

keytool -printcert -file test.cer

3. Java implementation using the certificate and keystore

package com.pack.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import javax.crypto.Cipher;

public class X509CertDemo {
    public static Certificate parseCert(String path) throws Exception {
        InputStream inStream = new FileInputStream(path);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        return cf.generateCertificate(inStream);
    }
    public static PublicKey getPublicKey(Certificate cert) {
        return cert.getPublicKey();
    }
    public static PrivateKey getPrivateKey(String storePath) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(new File(storePath)), "123123".toCharArray());
        Key key = keyStore.getKey("test", "123123".toCharArray());
        return (PrivateKey) key;
    }
    public static byte[] encrypt(Key key, String input) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(input.getBytes());
    }
    public static void decrypt(Key key, byte[] input) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] result = cipher.doFinal(input);
        System.out.println(new String(result));
    }
    public static void main(String[] args) throws Exception {
        String path = "f:\\secret\\test.cer";
        String storePath = "f:\\secret\\test.keystore";
        String input = "java@pack";
        PublicKey publicKey = getPublicKey(parseCert(path));
        byte[] secret = encrypt(publicKey, input);
        PrivateKey privateKey = getPrivateKey(storePath);
        decrypt(privateKey, secret);
        System.out.println("-----------------以上公钥加密私钥解密-----------------");
        System.out.println("-----------------以下私钥加密公钥解密-----------------");
        secret = encrypt(privateKey, input);
        decrypt(publicKey, secret);
    }
}

The program first encrypts with the public key and decrypts with the private key, then reverses the process, printing both results.

Notes

Asymmetric algorithms like RSA are much slower than symmetric ones and have strict limits on plaintext size (e.g., a 2048‑bit key can encrypt up to 245 bytes). Consequently, RSA is typically used to encrypt symmetric keys, such as those used in HTTPS.

End of tutorial.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaRSAcryptographyasymmetric encryptionkeytool
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.