JAVA RSA加密解密 分段加密解密

news/2025/2/11 19:57:45/

JAVA RSA加密解密 分段加密解密

package com.neusoft.caeid.upms.license;/*** @author dume* @create 2023-07-21 16:32**/import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
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;public class RSAUtil {public static final String KEY_ALGORITHM = "RSA";private static final String PUBLIC_KEY = "RSAPublicKey";private static final String PRIVATE_KEY = "RSAPrivateKey";/*** RSA最大加密明文大小*/private static final int MAX_ENCRYPT_BLOCK = 245;/*** RSA最大解密密文大小*/private static final int MAX_DECRYPT_BLOCK = 256;/*** 生成密钥对*/public static Map<String, Object> initKey() throws Exception {KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);//设置密钥对的bit数 越大越安全keyPairGen.initialize(2048);KeyPair keyPair = keyPairGen.generateKeyPair();//获取公钥RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();//获取私钥RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;}/*** 获取公钥字符串*/public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {//获得map中的公钥对象 转为key对象Key key = (Key) keyMap.get(PUBLIC_KEY);//编码返回字符串return encryptBASE64(key.getEncoded());}/*** 获得私钥字符串*/public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {//获得map中的私钥对象 转为key对象Key key = (Key) keyMap.get(PRIVATE_KEY);//编码返回字符串return encryptBASE64(key.getEncoded());}/*** 获取公钥*/public static PublicKey getPublicKey(String publicKeyString) throws NoSuchAlgorithmException, InvalidKeySpecException {byte[] publicKeyByte = Base64.getDecoder().decode(publicKeyString);X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);PublicKey publicKey = keyFactory.generatePublic(keySpec);return publicKey;}/*** 获取私钥*/public static PrivateKey getPrivateKey(String privateKeyString) throws Exception {byte[] privateKeyByte = Base64.getDecoder().decode(privateKeyString);PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);PrivateKey privateKey = keyFactory.generatePrivate(keySpec);return privateKey;}/*** BASE64解码 返回字节数组* key 需要解码的字符串*/public static byte[] decryptBASE64(String key) {return Base64.getDecoder().decode(key);}/*** BASE64编码返回加密字符串* key 需要编码的字节数组*/public static String encryptBASE64(byte[] key) throws Exception {return new String(Base64.getEncoder().encode(key));}/*** 公钥加密*/public static String encrypto(String text, String publicKeyStr) {try {System.out.println("明文lenth为"+text.length());Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));byte tempBytes[] = cipher.doFinal(text.getBytes());String secretText = Base64.getEncoder().encodeToString(tempBytes);return secretText;} catch (Exception e) {throw new RuntimeException("加密字符串[" + text + "]时遇到异常", e);}}/*** 私钥解密** @param secretText*/public static String decrypto(String secretText, String privateKeyStr) {try {//生成公钥Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyStr));// 密文解码byte[] secretText_decode = Base64.getDecoder().decode(secretText.getBytes());byte tempBytes[] = cipher.doFinal(secretText_decode);String text = new String(tempBytes);return text;} catch (Exception e) {throw new RuntimeException("解密字符串[" + secretText + "]时遇到异常", e);}}/*** 分段加密*/public static String encrypt(String plainText, String publicKeyStr) throws Exception {System.out.println("明文lenth为"+plainText.length());byte[] plainTextArray = plainText.getBytes();PublicKey publicKey = getPublicKey(publicKeyStr);Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, publicKey);int inputLen = plainTextArray.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;int i = 0;byte[] cache;while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(plainTextArray, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(plainTextArray, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] encryptText = out.toByteArray();out.close();return Base64.getEncoder().encodeToString(encryptText);}/*** 分段解密*/public static String decrypt(String encryptTextHex, String privateKeyStr) throws Exception {byte[] encryptText = Base64.getDecoder().decode(encryptTextHex);PrivateKey privateKey = getPrivateKey(privateKeyStr);Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, privateKey);int inputLen = encryptText.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_DECRYPT_BLOCK) {cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_DECRYPT_BLOCK;}byte[] plainText = out.toByteArray();out.close();return new String(plainText);}public static void main(String[] args) throws Exception {Map<String, Object> keyMap;String cipherText;String input = "数字测试爱上吃东西啊吃撒吃撒擦擦撒擦CCA擦擦擦C";try {keyMap = initKey();String publicKey = getPublicKeyStr(keyMap);System.out.println("公钥------------------");System.out.println(publicKey);System.out.println("length: " + publicKey.length());String privateKey = getPrivateKeyStr(keyMap);System.out.println("私钥------------------");System.out.println(privateKey);System.out.println("length: " + privateKey.length());cipherText = encrypt(input, publicKey);//加密后的东西System.out.println("密文=======" + cipherText);System.out.println("length: " + cipherText.length());//开始解密String plainText = decrypt(cipherText, privateKey);System.out.println("解密后明文===== " + plainText);} catch (Exception e) {e.printStackTrace();}}
}

http://www.ppmy.cn/news/1015526.html

相关文章

小白带你学习linux的Redis基础(三十二)

目录 前言 一、概述 1、NoSQL 2、Redis 二、安装 1、基础配置 2、编译安装 3、RPM安装网络源安装 三、目录结构 1、rpm -ql redis 2、/etc/redis.conf 四、命令解析 1、redis-server 2、redis-cli 2、redis-check-rdb 3、redis-check-aof 五、redis登录更改 …

在centos7下通过docker 安装onlyoffice

因为需要调试网盘&#xff0c;所以今天安装一下centos7的onlyoffice 官方介绍如下&#xff1a; 为了方便&#xff0c;还是通过docker方式来安装onlyoffice了&#xff0c;这里我们采用社区版本了。 1、下载docker安装包 如下&#xff1a; docker pull onlyoffice/documentserv…

深入理解 this

文章目录 1. 理解 this2. 为了进一步理解 this,我们再看一个案例3. this 的注意事项和使用细节 1. 理解 this 什么是 this&#xff1f; java虚拟机会给每一个对象分配 this&#xff0c;代表当前对象&#xff0c;坦白的讲&#xff0c;要明白 this不是件容易的事&#xff0c;打一…

XXL-Job 具体通过docker 配置,再通过springboot执行注册实现完整流程

【2023】XXL-Job 具体通过docker 配置安装容器&#xff0c;再通过springboot执行注册实现 一、概述二、安装1、拉取镜像2、创建数据库3、创建容器并运行3、查看容器和日志4、打开网页 127.0.0.1:9051/xxl-job-admin/ 三、实现注册测试1、创建一个SpringBoot项目、添加依赖。2、…

.NET 应用程序 部署

**硬件支持型号 点击 查看 硬件支持 详情** DTU701 产品详情 DTU702 产品详情 DTU801 产品详情 DTU802 产品详情 DTU902 产品详情 G5501 产品详情 本文内容 在设备上部署 dotnet应用&#xff0c;与任何其他平台的部署相同&#xff0c;可以2种方式&#xff1a; 依赖于框…

座舱开发的“道”与“术”

前言&#xff1a; 近年来&#xff0c;随着汽车“新四化”浪潮的兴起&#xff0c;软件定义已成为产业共识&#xff0c;将深度参与到整个汽车的定义、开发验证销售以及服务全过程。一方面确保软件可升级&#xff0c;跨车型、软件甚至跨车企软件重用。另一方面对于硬来讲&#xf…

系统集成项目成本管理

在项目中&#xff0c;成本是指项目活动或其组成部分的货币价值或价格&#xff0c;包括为实施、完成或创造该活动或其组成部分所需资源的货币价值。具体的成本一般包括直接工时、其他百接费用、间接工时、其他间接费用以及采购价格。 项目全过程所耗用的各种成本的总和为项目成本…

C/C++面试总结

一、关键字static、const、extern、volatile作用 1、const 1.修饰常量 用const修饰的变量是不可变的&#xff0c;修饰后的变量只能使用&#xff0c;不能修改。 2.修饰指针 如果const位于*的左侧&#xff0c;eg&#xff1a;const int* a&#xff0c;则const就是用来修饰指针…