Advertisement

RSA加密算法的实现

阅读量:

文章目录

引言

  1. 通过调用generatorKeyPair方法生成一组公私钥对
  2. 获取一组公私钥字符串
  3. 实现加解密功能
  4. 验证过程(附全部代码)

前言

因为从事银行相关工作对数据的安全性要求较高,在传输过程中必须对前后端之间的通信数据进行严格加密处理。因此开发一个简化的RSA加密算法工具类将有助于提升前后端在传递数据时的安全性水平。再次整理一下吧!通过这次分享希望能帮助到有需要的朋友!遇到问题的朋友可以在底部留言询问我会抽空时间帮大家解答这些问题!共同进步!一起加油!

一、第一步使用generatorKeyPair产生公私钥

第一步是生成generatorKeyPair对象(所选算法),并配置参数设置(加密位数)。随后利用该对象生成密钥对,并提取对应的公钥与私钥。最后将这些密钥整合后打包返回。

复制代码
     /** * 通过KeyPairGenerator产生公私钥
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String ,Object> generetorKeyPair() throws NoSuchAlgorithmException {
    
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    
        keyPairGenerator.initialize(INITIALIZE_LENGTH);
    
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
    
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
    
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    
        HashMap<String, Object> map = new HashMap<>();
    
        map.put("RSAPublicKey",rsaPublicKey);
    
        map.put("RSAPrivateKey",rsaPrivateKey);
    
        return map;
    
    
    }
    
    
    
    
    c
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-16/35nH4PdgwXWLq9QkGcx7uUYKtDij.png)

二、取出公私钥字符串

手动实现两个函数用于对公私钥进行Base64加密字符串处理(其中推荐使用java.util.Base64库实现此功能),从而提升公私钥的安全性。

复制代码
    /** * 拿到RSA公钥字符串
     * @param map
     * @return
     */
    public static String getRSAPublicKey(Map<String ,Object> map) {
    
        Key rsaPublicKey = (Key) map.get(PUBLIC_KEY);
    
        return Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());
    
    
    }
    
    /** *拿到RSA私钥字符串
     * @param map
     * @return
     */
    public static String getRSAPriateKey(Map<String ,Object> map) {
    
    
        Key rsaPrivateKey = (Key) map.get(PRIVATE_KEY);
    
        return Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded());
    
    }
    
    
    
    
    
    c
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-16/A4ylhQeq8z9aj6VrWK3vwUfTcnxX.png)

三、加解密算法

基于Cipher和解密类实现了RSA算法的高效加解密功能

复制代码
    
     /** * 使用公钥进行加密
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublic( byte[] data,String publicKey ) throws Exception {
    
        byte[] decode = Base64.getDecoder().decode(publicKey);
    
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode);
    
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(x509EncodedKeySpec);
    
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE,publicK);
    
        //如果加密明文长度小于规定的最大长度,如下直接加密就好,否则需要分段加密
        //cipher.doFinal(data);
    
    
        //以下为分段加密
    
        int length = data.length;
        int i=0;
        int offset=0;
        byte[] cache = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        while (length-offset>0) {
            if (length-offset>MAX_ENCRYPT_BLOCK) {
    
                cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
            }else {
                cache = cipher.doFinal(data,offset,length-offset);
            }
    
            baos.write(cache,0,cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptData = baos.toByteArray();
        baos.close();
        return encryptData;
    
    }
    
    /** * 使用私钥进行解密
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey( byte[] data,String privateKey ) throws Exception {
    
        byte[] decode = Base64.getDecoder().decode(privateKey);
    
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode);
    
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey publicK = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE,publicK);
    
        //如果解密明文长度小于规定的最大长度,如下直接解密就好,否则需要分段解密
        //cipher.doFinal(data);
    
        //以下为分段解密
    
        int length = data.length;
        int i=0;
        int offset=0;
        byte[] cache = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        while (length-offset>0) {
            if (length-offset>MAX_DECRYPT_BLOCK) {
    
                cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
    
            }else {
                cache = cipher.doFinal(data,offset,length-offset);
            }
            baos.write(cache,0,cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptData = baos.toByteArray();
        baos.close();
        return decryptData;
    
    }
    
    
    
    
    
    c
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-16/FBc9wMz6oxHytInGl5EskQjJpSD8.png)

该处使用的url网络请求的数据。


四、测试(附全码)

下面我们简单测试一下,随便传句话,试下效果。各位小伙伴们,如下所示:

复制代码
    package com.trs.util;
    
    import jdk.nashorn.internal.runtime.RewriteException;
    import org.omg.CORBA.PUBLIC_MEMBER;
    
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.security.*;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    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;
    
    /** * Demo class
     *一个简易版本的RSA加密算法的实现
     * @author crazy-water
     * @date 10/21/2021 6:43 PM
     */
    public class RSAUtil {
    
    //加密算法
    public static final  String KEY_ALGORITHM = "RSA";
    
    //RSA公钥
    public static final   String PUBLIC_KEY = "RSAPublicKey";
    
    //RSA私钥
    public static final String PRIVATE_KEY = "RSAPrivateKey";
    
    //1024位最大加密长度
    public static final int MAX_ENCRYPT_BLOCK = 117;
    
    //1024位最大解密长度
    public static final int MAX_DECRYPT_BLOCK = 128;
    
    //加密位数
    public static final int INITIALIZE_LENGTH = 1024;
    
    
    
    /** * 通过KeyPairGenerator产生公私钥
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static Map<String ,Object> generetorKeyPair() throws NoSuchAlgorithmException {
    
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    
        keyPairGenerator.initialize(INITIALIZE_LENGTH);
    
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
    
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
    
        RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
    
        HashMap<String, Object> map = new HashMap<>();
    
        map.put("RSAPublicKey",rsaPublicKey);
    
        map.put("RSAPrivateKey",rsaPrivateKey);
    
        return map;
    
    
    }
    
    
    /** * 拿到RSA公钥字符串
     * @param map
     * @return
     */
    public static String getRSAPublicKey(Map<String ,Object> map) {
    
        Key rsaPublicKey = (Key) map.get(PUBLIC_KEY);
    
        return Base64.getEncoder().encodeToString(rsaPublicKey.getEncoded());
    
    
    }
    
    /** *拿到RSA私钥字符串
     * @param map
     * @return
     */
    public static String getRSAPriateKey(Map<String ,Object> map) {
    
    
        Key rsaPrivateKey = (Key) map.get(PRIVATE_KEY);
    
        return Base64.getEncoder().encodeToString(rsaPrivateKey.getEncoded());
    
    }
    
    /** * 使用公钥进行加密
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublic( byte[] data,String publicKey ) throws Exception {
    
        byte[] decode = Base64.getDecoder().decode(publicKey);
    
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decode);
    
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(x509EncodedKeySpec);
    
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE,publicK);
    
        //如果加密明文长度小于规定的最大长度,如下直接加密就好,否则需要分段加密
        //cipher.doFinal(data);
    
    
        //以下为分段加密
    
        int length = data.length;
        int i=0;
        int offset=0;
        byte[] cache = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        while (length-offset>0) {
            if (length-offset>MAX_ENCRYPT_BLOCK) {
    
                cache = cipher.doFinal(data, offset, MAX_ENCRYPT_BLOCK);
            }else {
                cache = cipher.doFinal(data,offset,length-offset);
            }
    
            baos.write(cache,0,cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptData = baos.toByteArray();
        baos.close();
        return encryptData;
    
    }
    
    /** * 使用私钥进行解密
     * @param data
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey( byte[] data,String privateKey ) throws Exception {
    
        byte[] decode = Base64.getDecoder().decode(privateKey);
    
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decode);
    
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey publicK = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE,publicK);
    
        //如果解密明文长度小于规定的最大长度,如下直接解密就好,否则需要分段解密
        //cipher.doFinal(data);
    
        //以下为分段解密
    
        int length = data.length;
        int i=0;
        int offset=0;
        byte[] cache = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        while (length-offset>0) {
            if (length-offset>MAX_DECRYPT_BLOCK) {
    
                cache = cipher.doFinal(data, offset, MAX_DECRYPT_BLOCK);
    
            }else {
                cache = cipher.doFinal(data,offset,length-offset);
            }
            baos.write(cache,0,cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptData = baos.toByteArray();
        baos.close();
        return decryptData;
    
    }
    
    
    /** * 主函数测试
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
    
    
        Map<String, Object> map = generetorKeyPair();
    
        String rsaPublicKey = getRSAPublicKey(map);
        String rsaPriateKey = getRSAPriateKey(map);
        String  oldData = "各位小伙伴,新的一天继续加油哦";
        System.out.println("加密前的数据-----------"+oldData);
        byte[] encryptData = encryptByPublic(oldData.getBytes(), rsaPublicKey);
        byte[] decryptData = decryptByPrivateKey(encryptData, rsaPriateKey);
    
        System.out.println("解密后的数据-----------"+new String(decryptData));
    
    
    }
    
    
    }
    
    
    
    c
    
    
![](https://ad.itadn.com/c/weblog/blog-img/images/2025-08-16/XP2rNiD3lH6Ixu8J4O9c7eszdLTh.png)
在这里插入图片描述

测试结果显示图,请看下文内容。从下文可以看出实验结果准确无误。亲爱的小伙伴们都快来啦!星光不负有心人,请赶紧行动起来吧!

全部评论 (0)

还没有任何评论哟~