RSA in Java

本文使用 Java Security API 演示 RSA 算法的使用过程。

1 RSA 加密算法属于非对称加密算法,第一步需要生成密钥对

public static KeyPair initKeyPair()
    throws NoSuchAlgorithmException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
    keyPairGenerator.initialize(KEY_SIZE);
    return keyPairGenerator.generateKeyPair();
}

生成的 java.security.KeyPair 对象虽然已经实现了 java.io.Serializable 接口,但为了更方便存储和传输,常需要使用 Base64 编码成字符串。

public static Map<String, String> initKeys()
    throws NoSuchAlgorithmException {
    KeyPair keyPair = initKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    return new HashMap<String, String>() {{
        put(RSA_PUBLIC_KEY, Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        put(RSA_PRIVATE_KEY, Base64.getEncoder().encodeToString(privateKey.getEncoded()));
    }};
}

2 有了密钥对后就可以使用其中一个加密,使用另一个解密,首先给出公钥加密的代码片段

public static byte[] encryptByPublicKey(byte[] data, String key)
    throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException {
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return cipher.doFinal(data);
}

使用公钥加密后的密文只能使用私钥解密

public static byte[] decryptByPrivateKey(byte[] data, String key)
    throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException {
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

3 下面是使用私钥加密的代码片段

public static byte[] encryptByPrivateKey(byte[] data, String key)
    throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException {
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}

同样,使用私钥加密的密文只能使用公钥解密

public static byte[] decryptByPublicKey(byte[] data, String key)
    throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
    BadPaddingException, IllegalBlockSizeException {
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
    PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    return cipher.doFinal(data);
}

以上便是使用 Java 原生的 Security API 实现 RSA 加解密的工具代码,可以在此基础上进一步封装,如接收加解密的数据不止是 byte[] 类型,可以直接接收 String 或其他特殊类型的数据,返回的加解密后的结果也可以封装成 String 等其它类型。同一类型密钥的加解密代码中也存在大量重复代码,可以统一提取成样板代码。

以下是完整的 RSA 加解密工具类代码

package learn.spring.security.util;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils {
    
    private static final String ALGORITHM = "RSA";
    
    private static final int KEY_SIZE = 1024;
    
    public static final String RSA_PUBLIC_KEY = "RSA_PUBLIC_KEY";
    
    public static final String RSA_PRIVATE_KEY = "RSA_PRIVATE_KEY";
    
    /**
     * 生成密钥对
     */
    public static KeyPair initKeyPair()
        throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        return keyPairGenerator.generateKeyPair();
    }
    
    /**
     * 生成密钥对,并保存为 Map 对象
     */
    public static Map<String, String> initKeys()
        throws NoSuchAlgorithmException {
        KeyPair keyPair = initKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        return new HashMap<String, String>() {{
            put(RSA_PUBLIC_KEY, Base64.getEncoder().encodeToString(publicKey.getEncoded()));
            put(RSA_PRIVATE_KEY, Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        }};
    }
    
    /**
     * 公钥加密
     */
    public static byte[] encryptByPublicKey(byte[] data, String key)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }
    
    /**
     * 私钥解密
     */
    public static byte[] decryptByPrivateKey(byte[] data, String key)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
    
    /**
     * 私钥加密
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
    
    /**
     * 公钥解密
     */
    public static byte[] decryptByPublicKey(byte[] data, String key)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(key));
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }
}

附单元测试代码

package learn.spring.security.util;

import org.junit.Assert;
import org.junit.Test;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
import java.util.Objects;

public class RSAUtilsTests {
    
    @Test
    public void testInitKeyPair()
        throws NoSuchAlgorithmException {
        KeyPair keyPair = RSAUtils.initKeyPair();
        Assert.assertNotNull(keyPair);
        Assert.assertNotNull(keyPair.getPublic());
        Assert.assertNotNull(keyPair.getPrivate());
        Assert.assertNotEquals(keyPair.getPublic(), keyPair.getPrivate());
    }
    
    @Test
    public void testInitKeys()
        throws NoSuchAlgorithmException {
        Map<String, String> keys = RSAUtils.initKeys();
        for (Map.Entry<String, String> entry : keys.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            Assert.assertTrue(key.equals(RSAUtils.RSA_PUBLIC_KEY) || key.equals(RSAUtils.RSA_PRIVATE_KEY));
            Assert.assertTrue(Objects.nonNull(value) && !value.trim().equals(""));
        }
    }
    
    @Test
    public void testEncryptByPublicAndDecryptByPrivate()
        throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
        InvalidKeySpecException, NoSuchPaddingException {
        String msg = "Hello, RSA!";
        Map<String, String> keys = RSAUtils.initKeys();
        byte[] encryptedMsg = RSAUtils.encryptByPublicKey(msg.getBytes(), keys.get(RSAUtils.RSA_PUBLIC_KEY));
        byte[] decryptedMsg = RSAUtils.decryptByPrivateKey(encryptedMsg, keys.get(RSAUtils.RSA_PRIVATE_KEY));
        String restoredMsg = new String(decryptedMsg);
        System.out.println(restoredMsg);
        Assert.assertEquals(msg, restoredMsg);
    }
    
    @Test
    public void testEncryptByPrivateAndDecryptByPublic()
        throws NoSuchAlgorithmException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException,
        InvalidKeySpecException, NoSuchPaddingException {
        String msg = "Introduce RSA";
        Map<String, String> keys = RSAUtils.initKeys();
        byte[] encryptedMsg = RSAUtils.encryptByPrivateKey(msg.getBytes(), keys.get(RSAUtils.RSA_PRIVATE_KEY));
        byte[] decryptedMsg = RSAUtils.decryptByPublicKey(encryptedMsg, keys.get(RSAUtils.RSA_PUBLIC_KEY));
        String restoredMsg = new String(decryptedMsg);
        System.out.println(restoredMsg);
        Assert.assertEquals(msg, restoredMsg);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,306评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,657评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,928评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,688评论 0 220
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,105评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,024评论 1 225
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,159评论 2 318
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,937评论 0 212
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,689评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,851评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,325评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,651评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,364评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,192评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,985评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,154评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,955评论 2 279

推荐阅读更多精彩内容