Information Security 8 min read

Master RSA Encryption in Java: Theory, Code, and Execution

This article explains why asymmetric encryption like RSA is paired with symmetric algorithms, outlines RSA's history and key concepts, and provides a complete Java implementation with code examples and execution results, illustrating both public‑key and private‑key operations.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master RSA Encryption in Java: Theory, Code, and Execution

Asymmetric encryption algorithms are less efficient, so they are typically combined with symmetric algorithms: the asymmetric algorithm encrypts the symmetric key, while the symmetric algorithm encrypts the actual data, which is much faster.

Asymmetric algorithms impose limits on the length of data they can encrypt, which vary with key size.

In 1978, MIT researchers Ron Rivest, Adi Shamir, and Leonard Adleman introduced a new asymmetric encryption algorithm named RSA, after the initials of their surnames.

RSA is the international standard for asymmetric encryption. It can be used for data encryption as well as digital signatures. Compared with symmetric algorithms such as DES and AES, RSA is much slower. Symmetric encryption uses a single key, whereas asymmetric encryption uses a public key (open) and a private key (secret). The public key is shared with third parties, while the private key is kept confidential. Data encrypted with the public key must be decrypted with the matching private key, and data encrypted with the private key must be decrypted with the corresponding public key.

Java 7 (and similarly Java 8) implementation using Bouncy Castle.

Java code implementation:

<code>package com.pack.security.rsa;

import java.nio.charset.Charset;
import java.security.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.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

public class RSAMain {
    public static final String RSA_ALGORITHM = "RSA";
    public static final String PUBLIC_KEY = "RSAPublicKey";
    public static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA key length, default 1024
     */
    public static final int KEY_SIZE = 1024;

    /**
     * Initialize RSA key pair
     */
    public static Map<String, Key> initRSAKey() throws Exception {
        Map<String, Key> keys = new HashMap<>();
        // Instantiate key pair generator
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        // Initialize key length
        keyPairGenerator.initialize(KEY_SIZE);
        // Generate key pair
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        // Get public key
        PublicKey publicKey = keyPair.getPublic();
        // Get private key
        PrivateKey privateKey = keyPair.getPrivate();
        keys.put(PUBLIC_KEY, publicKey);
        keys.put(PRIVATE_KEY, privateKey);
        return keys;
    }

    /**
     * Get public key bytes
     */
    public static byte[] getPublicKey(Map<String, Key> keys) throws Exception {
        return keys.get(PUBLIC_KEY).getEncoded();
    }

    /**
     * Get private key bytes
     */
    public static byte[] getPrivateKey(Map<String, Key> keys) throws Exception {
        return keys.get(PRIVATE_KEY).getEncoded();
    }

    /**
     * Private key decryption
     */
    public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * Public key decryption
     */
    public static byte[] decryptByPublicKey(byte[] data, byte[] key) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    /**
     * Private key encryption
     */
    public static byte[] encryptByPrivateKey(byte[] data, byte[] key) throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * Public key encryption
     */
    public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }

    public static void main(String[] args) throws Exception {
        byte[] data = "JavaRSA算法".getBytes(Charset.forName("UTF-8"));
        Map<String, Key> keys = initRSAKey();
        // Private key encrypt, public key decrypt
        byte[] encryptDataPrivate = encryptByPrivateKey(data, getPrivateKey(keys));
        System.out.println("私钥加密,公钥解密: " + new String(decryptByPublicKey(encryptDataPrivate, getPublicKey(keys)), "UTF-8"));
        // Public key encrypt, private key decrypt
        byte[] encryptDataPublic = encryptByPublicKey(data, getPublicKey(keys));
        System.out.println("公钥加密,私钥解密: " + new String(decryptByPrivateKey(encryptDataPublic, getPrivateKey(keys)), "UTF-8"));
    }
}
</code>

The code comments are comprehensive, so no further explanation is provided.

Execution result:

Done!!!

JavaRSAdigital signaturecryptographyasymmetric encryption
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

login 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.