代码中采用了Base64 对应的Maven仓库地址

<!-- http://mvnrepository.com/artifact/net.iharder/base64 -->
<dependency><groupId>net.iharder</groupId><artifactId>base64</artifactId><version>2.3.9</version>
</dependency>

Java源代码如下

package org.utils.code;import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
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.RSAPrivateCrtKey;
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.HashMap;
import java.util.Map;import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;import net.iharder.Base64;public class RSAUtils {public static final String KEY_ALGORITHM = "RSA";private static final String PUBLIC_KEY = "publicKey";private static final String PRIVATE_KEY = "privateKey";/*** RSA最大加密明文大小*/private static final int MAX_ENCRYPT_BLOCK = 117;/*** RSA最大解密密文大小*/private static final int MAX_DECRYPT_BLOCK = 128;/*** @Title: publicKeyToString* @Description: 得到字符串型的公钥 Java* @param publicKey* @return String*/public static String publicKeyToString(RSAPublicKey publicKey) {return Base64.encodeBytes(publicKey.getEncoded());}/*** @Title: privateKeyToString* @Description: 得到字符串型的私钥 Java* @param privateKey* @return String*/public static String privateKeyToString(RSAPrivateKey privateKey) {return Base64.encodeBytes(privateKey.getEncoded());}/*** @Title: getPublicKey* @Description: 将字符串型公钥转化为PublicKey Java* @param publicKey* @return PublicKey*/public static PublicKey getPublicKey(String publicKey) {try {X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decode(publicKey));KeyFactory factory;factory = KeyFactory.getInstance(KEY_ALGORITHM);return factory.generatePublic(x509EncodedKeySpec);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeySpecException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}/*** @Title: getPrivateKey* @Description: 将字符串型私钥转化为 PrivateKey Java* @param privateKey* @return PrivateKey*/public static PrivateKey getPrivateKey(String privateKey) {try {PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decode(privateKey));KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);return factory.generatePrivate(pkcs8EncodedKeySpec);} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (InvalidKeySpecException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}/*** @Title: generateKeyBytes* @Description: 初始化密钥对* @return Map<String,Object>*/public static Map<String, Object> generateKeyBytes() {KeyPairGenerator keyPairGen;try {keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);keyPairGen.initialize(1024);KeyPair keyPair = keyPairGen.generateKeyPair();RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();Map<String, Object> keyMap = new HashMap<String, Object>(2);keyMap.put(PUBLIC_KEY, publicKey);keyMap.put(PRIVATE_KEY, privateKey);return keyMap;} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return null;}/*** @Title: RSAEncode* @Description: 将字符串加密* @param key* @param plainText* @return String*/public static String RSAEncode(PublicKey key, String plainText) {byte[] b = plainText.getBytes();try {int inputLen = b.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, key);// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(b, offSet, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(b, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_ENCRYPT_BLOCK;}byte[] decryptedData = out.toByteArray();out.close();return Base64.encodeBytes(decryptedData);} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException| BadPaddingException | IOException e) {e.printStackTrace();}return null;}/*** @Title: RSADecode* @Description: 将字符串解密* @param key* @param encodedText* @return String*/public static String RSADecode(PrivateKey key, String encodedText) {try {byte[] b = Base64.decode(encodedText);int inputLen = b.length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offSet = 0;byte[] cache;int i = 0;Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, key);// 对数据分段解密while (inputLen - offSet > 0) {if (inputLen - offSet > MAX_DECRYPT_BLOCK) {cache = cipher.doFinal(b, offSet, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(b, offSet, inputLen - offSet);}out.write(cache, 0, cache.length);i++;offSet = i * MAX_DECRYPT_BLOCK;}byte[] decryptedData = out.toByteArray();out.close();return new String(decryptedData);} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException| BadPaddingException | IOException e) {e.printStackTrace();}return null;}/*** @Title: getRSAPrivateKeyAsNetFormat* @Description: 将Java私钥转化为.Net格式* @param privateKey* @return String*/public static String getRSAPrivateKeyAsNetFormat(String privateKey) {try {StringBuffer buff = new StringBuffer(1024);PKCS8EncodedKeySpec pvkKeySpec = new PKCS8EncodedKeySpec(getPrivateKey(privateKey).getEncoded());KeyFactory keyFactory = KeyFactory.getInstance("RSA");RSAPrivateCrtKey pvkKey = (RSAPrivateCrtKey) keyFactory.generatePrivate(pvkKeySpec);buff.append("<RSAKeyValue>");buff.append("<Modulus>" + Base64.encodeBytes(removeMSZero(pvkKey.getModulus().toByteArray())) + "</Modulus>");buff.append("<Exponent>" + Base64.encodeBytes(removeMSZero(pvkKey.getPublicExponent().toByteArray()))+ "</Exponent>");buff.append("<P>" + Base64.encodeBytes(removeMSZero(pvkKey.getPrimeP().toByteArray())) + "</P>");buff.append("<Q>" + Base64.encodeBytes(removeMSZero(pvkKey.getPrimeQ().toByteArray())) + "</Q>");buff.append("<DP>" + Base64.encodeBytes(removeMSZero(pvkKey.getPrimeExponentP().toByteArray())) + "</DP>");buff.append("<DQ>" + Base64.encodeBytes(removeMSZero(pvkKey.getPrimeExponentQ().toByteArray())) + "</DQ>");buff.append("<InverseQ>" + Base64.encodeBytes(removeMSZero(pvkKey.getCrtCoefficient().toByteArray()))+ "</InverseQ>");buff.append("<D>" + Base64.encodeBytes(removeMSZero(pvkKey.getPrivateExponent().toByteArray())) + "</D>");buff.append("</RSAKeyValue>");return buff.toString();} catch (Exception e) {System.err.println(e);return null;}}/*** @Title: getRSAPublicKeyAsNetFormat* @Description: 将Java公钥转化为.Net格式* @param encodedPublicKey* @return String*/public static String getRSAPublicKeyAsNetFormat(String publicKey) {try {StringBuffer buff = new StringBuffer(1024);KeyFactory keyFactory = KeyFactory.getInstance("RSA");RSAPublicKey pukKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(getPublicKey(publicKey).getEncoded()));buff.append("<RSAKeyValue>");buff.append("<Modulus>" + Base64.encodeBytes(removeMSZero(pukKey.getModulus().toByteArray())) + "</Modulus>");buff.append("<Exponent>" + Base64.encodeBytes(removeMSZero(pukKey.getPublicExponent().toByteArray()))+ "</Exponent>");buff.append("</RSAKeyValue>");return buff.toString();} catch (Exception e) {System.err.println(e);return null;}}/*** @Title: removeMSZero* @Description: JAVA和.Net密钥转化算法* @param data* @return byte[]*/private static byte[] removeMSZero(byte[] data) {byte[] temp;int len = data.length;if (data[0] == 0) {temp = new byte[data.length - 1];System.arraycopy(data, 1, temp, 0, len - 1);} elsetemp = data;return temp;}public static void main(String[] args) {Map<String, Object> map = generateKeyBytes();String publicKey = publicKeyToString((RSAPublicKey) map.get(PUBLIC_KEY));String privateKey = privateKeyToString((RSAPrivateKey) map.get(PRIVATE_KEY));System.out.println("生成的公钥Java--> " + publicKey);System.out.println("生成的公钥.Net--> " + getRSAPublicKeyAsNetFormat(publicKey));System.out.println("生成的私钥Java--> " + privateKey);System.out.println("生成的私钥.Net--> " + getRSAPrivateKeyAsNetFormat(privateKey));String dataText = "这是需要加密的数据,RSA加密明文长度为117字节 所以我这里采用了分段加密和分段解密";System.out.println("加密前--> " + dataText);String ciphertext = RSAEncode(getPublicKey(publicKey), dataText);System.out.println("加密后--> " + ciphertext);System.out.println("解密后--> " + RSADecode(getPrivateKey(privateKey), ciphertext));}
}

闲暇时还写了个小工具 张这样需要的也可以下载 点击打开链接

RSA分段加密分段解密以及密钥与.Net的转化相关推荐

  1. RSA非对称加密和解密(同时生成密钥)

    RSA非对称加密和解密(同时生成密钥) 准备jar包 bcprov-jdk16-1.46.jar commons-codec-1.15.jar 获取jar地址:https://mvnrepositor ...

  2. DES和RSA混合加密及解密-JAVA

    DES和RSA混合加密及解密 实际开发过程中,RSA生成的公钥应保存在加密方,私钥应保存在解密方,可使用读取文件内容方式获取密钥. maven依赖: <!-- DES --><dep ...

  3. RSA前端加密后端解密

    前面说过接口数据在后端如何使用RSA加解密 这里遇到了使用RSA前端加密后端解密的需求. 实现方式如下: 1.后端的RSA工具 package com.ieslab.interactivequery. ...

  4. Android实现公共公钥加密私钥解密(可分段加密分段解密)

    公私钥在线生成在线生成公钥私钥 public class MainActivity extends AppCompatActivity {@BindView(R.id.tv_name)TextView ...

  5. C#.NET Rsa私钥加密公钥解密

    在C#中,RSA私钥只能签名,不能加密,如果要加密,要借助BouncyCastle库. nuget 中引用 Portable.BouncyCastle. 工具类: RsaEncryptUtil usi ...

  6. RSA前台加密后台解密

    前台代码 这里注意引入的js为jsencrypt.min.js <!DOCTYPE html> <html><head><script>if (wind ...

  7. php signature解密,openssl RSA非对称加密、解密、签名、验签

    需要先了解的openssl系列函数 openssl_pkey_get_private 从证书中解析获取私钥,以供使用.成功,返回真实的密钥资源标识符(Resource ID),否则返回false op ...

  8. [引]生成加密和解密的密钥

    1.对称密钥 2.不对称密钥 3.将非对称密钥存储在密钥容器中 4.将非对称密钥存储在密钥容器中示例 =============================== 创建和管理密钥是加密过程的一个重要 ...

  9. RSA加密算法加密与解密过程解析

    1.加密算法概述 加密算法根据内容是否可以还原分为可逆加密和非可逆加密. 可逆加密根据其加密解密是否使用的同一个密钥而可以分为对称加密和非对称加密. 所谓对称加密即是指在加密和解密时使用的是同一个密钥 ...

最新文章

  1. 如此精心整理的深度学习资源只在这里,值得你拥有!(上篇)
  2. 【小白学习PyTorch教程】十四、迁移学习:微调ResNet实现男人和女人图像分类
  3. Puppet实战笔记
  4. windows删除桌面ie_从Windows 8“开始”屏幕启动IE的桌面版本
  5. 服务器kvm切换器维修,KVM切换器常见问题
  6. log4j 不同功能,同INFO级别,输出到不同log文件
  7. python 类和对象 有必要学吗_Python学习——对类和对象的初步理解,初识,与
  8. linux mint 安装内核,使用Ukuu在Ubuntu/Linux Mint上安装Linux Kernel 5.0的方法
  9. 【设计模式】之单例模式
  10. python读取文件格式化方法
  11. 缠中说禅电子书_缠中说禅108课PDF电子书
  12. mac下Charles https抓包乱码,手机不能上网解决
  13. centos mysql5.6卸载_centos 卸载mysql
  14. WEB学习——JQury
  15. Three.js 剖切模型功能封装
  16. 深圳哪家服务器速度最快,深圳区域该选择腾讯云哪个节点好?
  17. HOW TO:设置默认打印机
  18. 基于Python实现的默克尔树
  19. 国内无线通信模组企业(TOP 80)
  20. Spotify Mac版(音乐播放器)

热门文章

  1. REST-Assured,接口自动化的 “瑞士军刀“- 初识篇
  2. Table does not have the identity property. Cannot perform SET operation.
  3. 移动端:苹果开发者账号Apple Developer Program
  4. 浅谈teamtalk
  5. PNAS:睡眠的fMRI频谱特征
  6. unity SteamVR利用手柄合理移动
  7. Java学习-API
  8. 2021年上半年全球首席执行官任命达到创纪录水平,女性首席执行官翻了一番|美通社头条...
  9. 云起实验室:基于Redis实现在线游戏积分排行榜
  10. LeetCode(力扣) 刷题注意事项 持续更新 ~ ~