前言
- 简介
RSA 公开密钥明码体制是一种应用不同的加密密钥与解密密钥,“由已知加密密钥推导出解密密钥在计算上是不可行的”明码体制。 - 原理
依据数论,寻求两个大素数比较简单,而将它们的乘积进行因式分解却极其艰难,因而能够将乘积公开作为加密密钥,即公钥,而两个大素数组合成私钥。公钥是可公布的供任何人应用,私钥则为本人所有,供解密之用。 - 运算速度
因为进行的都是大数计算,使得 RSA 最快的状况也比 DES 慢上好几倍,无论是软件还是硬件实现。速度始终是 RSA 的缺点。一般来说只用于大量数据加密。RSA 的速度比对应同样安全级别的对称明码算法要慢 1000 倍左右。 - 其它链接
RSA 加密 – Vue
RSA 分段加密 – Java
RSA 分段解密 – Vue
具体实现
-
实现类
import javax.crypto.Cipher; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; /** * @Description RSA 加密算法 * @author coisini * @date Jul 5, 2021 * @Version 1.0 */ public class RSAUtil { private static final String ALGO = "RSA"; private static final String CHARSET = "UTF-8"; /** * 公钥 由 generateKeyPair()生成 */ private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaaI4MBywkCjIppZnraqN3pbrcZTq/t0+aMBo8K3pK9BDD6XkM6N2Yfcva7BSFbUWuAcI7piXak0UKn9CElDuhNzUSgQn4IXKxIt3Iva5cV83qYumj+0yRjjLT8Muu1Y1rgBZjY9oBwhVoV+Twg25+UJ+6Q6HM4xTwQQJDoyy4jwIDAQAB"; /** * 私钥 由 generateKeyPair()生成 */ private static final String PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJpojgwHLCQKMimlmetqo3elutxlOr+3T5owGjwrekr0EMPpeQzo3Zh9y9rsFIVtRa4BwjumJdqTRQqf0ISUO6E3NRKBCfghcrEi3ci9rlxXzepi6aP7TJGOMtPwy67VjWuAFmNj2gHCFWhX5PCDbn5Qn7pDoczjFPBBAkOjLLiPAgMBAAECgYBnBBKhG7frY5IMDxwd4Euna767hB4qAlbte+JE+ozgrOzyiDXm0wXk0yjKqm8WhczTRwEbYsImjdKmP/GSQoN1AU7yEzM8j0Jgq46m9ZVrHhu2NpuZpr+XueWnA6FNz6tybBgcCwA4t8dvfbOrvjqhrCu01O1xWIpjronyFBN4IQJBAPGuF58xjXyANnp5YU8NhUQ73tTIveRlOpMXDSYkf9lWG26XIGUIsTe0f5jssiNmYtxG+lUm9LLfZgOLcrVkDZ0CQQCjjrBNMXub49efVTCg+nCGT2QXW2BHg/qs5vu8Y34LUHoD/hoEJ+AOWOdnhpRoYOpBwJAm3Gu4a1VmZGGafp0bAkAdfY3aWhSWtZpwNXF/UPoLCnc1Zc1uGkAchLqRBfEn1w7/3qcQTRA66OaNBYzzLuIvWOXhECDZ1tK+6fw0UCItAkAOLibW6n1fDKf7JnWq30u2OVfiNofoa2bmarhUowOgk3+grP0wcwyX8dlOPnrLeeuVe86DsASe3p9u2zEjJesVAkEAhkLiv4TXrC1QlJl7ghksUfFmdT7M4Zxlzj10ConMgq68HkLdmn2nNLsjhUHGwJe3EqM6aozn4zw/Z7uPIT9Fsw=="; /** * 生成密钥对 * @throws NoSuchAlgorithmException */ private static void generateKeyPair() throws NoSuchAlgorithmException { // KeyPairGenerator 类用于生成公钥和私钥对,基于 RSA 算法生成对象 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGO); // 初始化密钥对生成器,密钥大小为 96-1024 位 keyPairGen.initialize(1024, new SecureRandom()); // 生成一个密钥对,保留在 keyPair 中 KeyPair keyPair = keyPairGen.generateKeyPair(); // 失去私钥 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 失去公钥 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); String publicKeyString = new String(Base64.getEncoder().encode(publicKey.getEncoded())); // 失去私钥字符串 String privateKeyString = new String(Base64.getEncoder().encode((privateKey.getEncoded()))); System.out.println(publicKeyString); System.out.println(privateKeyString); } /** * RSA 公钥加密 * @param data 加密字符串 * @return 密文 * @throws Exception 加密过程中的异样信息 */ private static String encryptByPublicKey(String data) throws Exception { // base64 编码的公钥 byte[] decoded = Base64.getDecoder().decode(PUBLIC_KEY); RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance(ALGO).generatePublic(new X509EncodedKeySpec(decoded)); // RSA 加密 Cipher cipher = Cipher.getInstance(ALGO); // 公钥加密 cipher.init(Cipher.ENCRYPT_MODE, pubKey); return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes(CHARSET))); } /** * RSA 私钥解密 * @param data 加密字符串 * @return 明文 * @throws Exception 解密过程中的异样信息 */ private static String decryptByPrivateKey(String data) throws Exception {byte[] inputByte = Base64.getDecoder().decode(data.getBytes(CHARSET)); // base64 编码的私钥 byte[] decoded = Base64.getDecoder().decode(PRIVATE_KEY); RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance(ALGO).generatePrivate(new PKCS8EncodedKeySpec(decoded)); // RSA 解密 Cipher cipher = Cipher.getInstance(ALGO); // 私钥解密 cipher.init(Cipher.DECRYPT_MODE, priKey); return new String(cipher.doFinal(inputByte)); } /** * 私钥加密 * 前端公钥解密 * @param data 加密字符串 * @return 密文 * @throws Exception 加密过程中的异样信息 */ public static String encryptByPrivateKey(String data) throws Exception { // 获取私钥 PrivateKey privateKey = getPrivateKey(PRIVATE_KEY); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] cipherText = cipher.doFinal(data.getBytes()); String cipherStr = Base64.getEncoder().encodeToString(cipherText); return cipherStr; } /** * 公钥解密 * @param data 解密字符串 * @return 明文 * @throws Exception 解密过程中的异样信息 */ public static String decryptByPublicKey(String data) throws Exception { // 获取公钥 PublicKey publicKey = getPublicKey(PUBLIC_KEY); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] cipherText = Base64.getDecoder().decode(data); byte[] decryptText = cipher.doFinal(cipherText); return new String(decryptText); } /** * 将 base64 编码后的私钥字符串转成 PrivateKey 实例 * @param privateKey 私钥 * @return PrivateKey 实例 * @throws Exception 异样信息 */ private static PrivateKey getPrivateKey(String privateKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(privateKey); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGO); return keyFactory.generatePrivate(keySpec); } /** * 将 base64 编码后的公钥字符串转成 PublicKey 实例 * @param publicKey 公钥 * @return PublicKey 实例 * @throws Exception 异样信息 */ private static PublicKey getPublicKey(String publicKey) throws Exception {byte[] keyBytes = Base64.getDecoder().decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(ALGO); return keyFactory.generatePublic(keySpec); } public static void main(String[] args) { String data = "RSA encrypt!"; try {// generateKeyPair(); String encryDataByPublicKey = encryptByPublicKey(data); System.out.println("encryDataByPublicKey:" + encryDataByPublicKey); String decryDataByPrivateKey = decryptByPrivateKey(encryDataByPublicKey); System.out.println("decryDataByPrivateKey:" + decryDataByPrivateKey); String encryDataByPrivateKey = encryptByPrivateKey(data); System.out.println("encryDataByPrivateKey:" + encryDataByPrivateKey); String decryDataByPublicKey = decryptByPublicKey(encryDataByPrivateKey); System.out.println("decryDataByPublicKey:" + decryDataByPublicKey); } catch (Exception e) {e.printStackTrace(); } } }
- 后果如下所示:
源码
- GitHub:https://github.com/Maggieq8324/coisini-rsa
- Gitee:https://gitee.com/maggieq8324/coisini-rsa