Java---RSA私钥加密解密,公钥加密解密--方法_java rsa公钥解密_系子818的博客-程序员宅基地

技术标签: spring boot  java  java-ee  开发语言  


package com.my.demo.utils;
 
import com.my.demo.common.Constants;
import com.my.experiment.exception.OptException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;
 
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
 
 
 
@Component
public class RsaUtil {

/**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RsaUtil .class);

    private static final String KEY_ALGORITHM = "RSA";
    private static final String PK = Constants.getPublicKey();
    private static final String SK = Constants.getPrivateKey();
 
    /**
     * 使用RSA公钥加密
     */
 
    public static String encryptByPublicKey(String str) {
        return Base64.encodeBase64String(getMaxResultEncrypt(str, getPublicKey(Cipher.ENCRYPT_MODE)));
    }
    /**
     * 使用公钥解密
     */
    public static String decryptByPublicKey(String data) {
        try {
            return new String(getMaxResultDecrypt(data, getPublicKey(Cipher.DECRYPT_MODE)));
        }catch (Exception e){
            throw new OptException("解密失败|"+e.getMessage());
        }
    }
    /**
     * 使用RSA私钥解密
     *
     * @param str 加密字符串
     */
    public static String decryptByPrivateKey(String str) {
        return new String(getMaxResultDecrypt(str, getPrivateKey(Cipher.DECRYPT_MODE)));
    }
 
    /**
     * 使用RSA私钥加密
     * @param data       加密数据
     */
    public static String encryptByPrivateKey(String data) {
        try {
            return Base64.encodeBase64String(getMaxResultEncrypt(data, getPrivateKey(Cipher.ENCRYPT_MODE)));
        } catch (Exception e) {
            throw new OptException("加密失败|"+e.getMessage());
        }
    }
    /**
     * 当长度过长的时候,需要分割后加密 117个字节
     */
    private static byte[] getMaxResultEncrypt(String str, Cipher cipher){
        try {
            byte[] inputArray = str.getBytes(StandardCharsets.UTF_8.name());
            int inputLength = inputArray.length;
            // 最大加密字节数,超出最大字节数需要分组加密
            int maxEncryptBlock = 117;
            // 标识
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache;
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > maxEncryptBlock) {
                    cache = cipher.doFinal(inputArray, offSet, maxEncryptBlock);
                    offSet += maxEncryptBlock;
                } else {
                    cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }
            return resultBytes;
        }catch (Exception e){
            e.printStackTrace();
            throw new OptException("加密处理失败,"+e.getMessage());
        }
    }
 
    /**
     * 当长度过长的时候,需要分割后解密 128个字节
     */
    private static byte[] getMaxResultDecrypt(String str, Cipher cipher) {
        try {
            byte[] inputArray = Base64.decodeBase64(str.getBytes(StandardCharsets.UTF_8.name()));
            int inputLength = inputArray.length;
            // 最大解密字节数,超出最大字节数需要分组加密
            int maxEncryptBlock = 128;
            int offSet = 0;
            byte[] resultBytes = {};
            byte[] cache;
            while (inputLength - offSet > 0) {
                if (inputLength - offSet > maxEncryptBlock) {
                    cache = cipher.doFinal(inputArray, offSet, maxEncryptBlock);
                    offSet += maxEncryptBlock;
                } else {
                    cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                    offSet = inputLength;
                }
                resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
                System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
            }
            return resultBytes;
        }catch (Exception e){
            e.printStackTrace();
            throw new OptException("解密数据处理异常,"+e.getMessage());
        }
    }
    /**
     * 根据加解密类型处理公钥
     *
     */
    public static Cipher getPublicKey(int mode) {
        try {
            String publicKey = formatString(PK);
            byte[] decoded = Base64.decodeBase64(publicKey);
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decoded);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey key = keyFactory.generatePublic(x509EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(mode, key);
            return cipher;
        } catch (Exception e) {
            throw new OptException("转换公钥异常====>>" + e.getMessage());
        }
    }
 
    /**
     * 根据加解密类型处理私钥
     */
    public static Cipher getPrivateKey(int mode) {
        try {
            //mode 加解密模式 ENCRYPT_MODE = 1  DECRYPT_MODE = 2
            String privateKey = formatString(SK);
            byte[] decoded = Base64.decodeBase64(privateKey);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decoded);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey key = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(mode, key);
            return cipher;
        } catch (Exception e) {
            throw new OptException("转换私钥异常====>>" + e.getMessage());
        }
    }
    public static String formatString(String source) {
        if (source == null) {
            return null;
        }
        return source.replace("\\r", "").replace("\\n", "").trim().replace(" ","");
    }
    public static void main(String[] args) throws Exception {
        String xxStr = "的发挥很大的22@@@";
        //加密
        String bytes1 = RsaUtil.encryptByPrivateKey(xxStr);
        String bytes2 = RsaUtil.encryptByPublicKey(xxStr);
        log.info("公钥加密2:{}",bytes2);
        log.info("私钥加密1:{}",bytes1);
 
        //解密
        log.info("私钥解密密2:{}",RsaUtil.decryptByPrivateKey(bytes2));
        log.info("公钥解密密1:{}",RsaUtil.decryptByPublicKey(bytes1));
 
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/m0_57085190/article/details/124703637

智能推荐

Qt控件--QComboBox_duplicatesenabled_Simple_core的博客-程序员宅基地

Qt控件--QComboBoxQComboBox属性editable : boolcurrentText : QStringcurrentIndexmaxVisibleItems : intmaxCount : intinsertPolicy : InsertPolicysizeAdjustPolicy : SizeAdjustPolicyminimumContentsLength : inticonSize : QSizeduplicatesEnabled : boolframe : boolmodelC_duplicatesenabled

新版WIN10 [20H2(2009)及以上] 换回旧版电脑系统属性界面的几种方法_hkey_local_machine\system\currentcontrolset\contro-程序员宅基地

 方法一:彻底回复旧的系统信息界面  1、打开注册表,然后找到以下两个路径:HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\FeatureManagement\Overrides\0\2093230218HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FeatureManagement\Overrides\0\2093230218​  2、均将EnabledState的值改为1._hkey_local_machine\system\currentcontrolset\control\featuremanagement\overri

VS2005 在编译C++时候遇到的错误和警告-程序员宅基地

warning C4172: returning address of local variable or temporary: 出现情况:在一个函数中定义了一个数组char c[],但是返回值为指针c。 原因说明:局部变量的生命周期已经结束,它的空间已经释放,返回它的地址是不安全的行为。返回后c会出现乱码。 解决方案:把char c[],定义为 static char []。

特征值,特征向量,特征多项式_有相同特征函数可交换-程序员宅基地

特征值与特征向量设 A\mathscr{A}A 是数域 PPP 上线性空间 VVV 的一个线性变换,如果对于数域 PPP 中一数 λ0\lambda_0λ0​ ,存在一个非零向量 ξ\xiξ 使得Aξ=λ0ξ\mathscr{A} \xi = \lambda_0\xiAξ=λ0​ξ那么 λ0\lambda_0λ0​ 称为 A\mathscr{A}A 的一个特征值,而 ξ\xiξ 称为 A\mathscr{A}A 的数域特征值 λ0\lambda_0λ0​ 的一个特征向量特征多项式设 AAA 是_有相同特征函数可交换

JS程序|盛最多水的容器-程序员宅基地

题目来源:力扣先来一下题目描述:给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点(i,ai) 。在坐标内画 n 条垂直线,垂直线 i的两个端点分别为(i,ai) 和 (i, 0)。找出其中的两条线,使得它们与x轴共同构成的容器可以容纳最多的水。说明:你不能倾斜容器,且n的值至少为 2。解题思路:这个很容易想到的是暴力求解的方法,两层for循环,设置一个默认最大值就可以得出最大的面积。确实这个方法拍脑袋就可以想到。但是有没有更优的方法呢,是有的。...

SeekBar 设置任意区间负数_seekbar 负数-程序员宅基地

首先上一张图片 布局文件 <?xml version="1.0" encoding="utf-8"?><LinearLayout ="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:lay..._seekbar 负数

随便推点

r语言 python 股票_R语言:抓取股票数据并存入数据库进行分析实例 MySQL-程序员宅基地

R语言连接mySql准备:RODBCR studio console下> Install.packages(RODBC)安装MySqlhttps://dev.mysql.com/get/Downloads/MySQLInstaller/mysql-installer-community-8.0.12.0.msi配置ODBCa) 控制面板系统和安全管理工具数据源(odbc)b) 点击系统...

算法提高 搬运冰块_算法 搬运冰块-程序员宅基地

算法提高 搬运冰块问题描述  丑枫接到了一份奇葩的工作:往冰库里搬运冰块.冰库外放着N箱冰块,由于室外温度高,冰块会很快融化,且每箱冰块的融化速度不同.因为每箱冰块的体积,质量不等,把每箱冰块搬运进冰块花费的时间也不同.因此需要合理安排搬运顺序,才能使总的冰块融化量最小.丑枫请你帮忙计算最少的总融化量是多少,以便汇报上司.输入格式  第一行输入整数N  接下来N行,每行两个整数,分别表示每箱冰块的搬运耗时Ti及融化速度Di.输出格式  输出最少的总融化量样例输入66 14 54 3_算法 搬运冰块

Depthwise卷积与Pointwise卷积_depthwise和pointwise_Good@dz的博客-程序员宅基地

Depthwise(DW)卷积与Pointwise(PW)卷积,合起来被称作Depthwise Separable Convolution(参见Google的Xception),该结构和常规卷积操作类似,可用来提取特征,但相比于常规卷积操作,其参数量和运算成本较低。所以在一些轻量级网络中会碰到这种结构如MobileNet。常规卷积操作对于一张55像素的三通道彩色图片,经过33卷积核(假设输出通道为4,卷积核为4个333的卷积核),最终输出4个特征图.如果有same padding则尺寸与输入层相同(5*_depthwise和pointwise

HTML基础_"<font size=1-2 color=\"\" face=\"\"></font><!--注释_缨玖的博客-程序员宅基地

HTML文档结构<html> <head> <meta charset="UTF-8"> <title>题目</title> </head> <body> <h1>一级标题</h1> … </body></html>HTML常用标签meta标签<meta http-equivalent="" content=""_""

HMM学习最佳范例七:前向-后向算法5-程序员宅基地

七、前向-后向算法(Forward-backward algorithm)  上一节我们定义了两个变量及相应的期望值,本节我们利用这两个变量及其期望值来重新估计隐马尔科夫模型(HMM)的参数pi,A及B:  如果我们定义当前的HMM模型为,那么可以利用该模型计算上面三个式子的右端;我们再定义重新估计的HMM模型为,那么上面三个式子的左端就是重估的HMM模型参数。Baum及他