rsa加密解密java和C#互通

前言

因为第三方项目是java的案例,但是原来的项目使用的是java,故需要将java代码转化为C#代码,其中核心代码就是RSA加密以及加签和验签,其他的都是api接口请求难度不大。

遇到的问题

java和c#密钥格式不一致,java使用的是base64格式的密钥,c#使用的是pem格式

公钥

公钥格式解释
pem“-----BEGIN RSA PUBLIC KEY-----”、中间的数据、“-----END RSA PUBLIC KEY-----” C#常用
ASN.1一般用base64编码格式编码 java常用

私钥

公钥格式解释
PKCS#1c#常用
PKCS#8java常用

证书类型

证书类型
X.509证书X.509只包含公钥,没有私钥,这种证书一般公开发布,可用于放在客服端使用,用于加密、验签
PKCS#7证书因为X.509证书只包含公钥,但有些时候我们需要把私钥和公钥合并成一个证书,放在服务端使用,用于解密、签名。PKCS#12就定义了这样一种证书,它既包含了公钥有包含了私钥。典型的入pfx、p12证书就是PKCS#12证书。
PKCS#12证书PKCS#7定义了证书链的类型结构

解决过程

C#和java密钥格式相互转换

这是一个想到的办法,java和c#密钥相互转换,这样密钥就统一了,大家相互加密解密不就可以了
c#代码,添加BouncyCastle.NetCore包
CryptoHelper

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Xml;namespace RSAStu05
{public class CryptoHelper{/// <summary>/// RSA密钥转Pem密钥/// </summary>/// <param name="RSAKey">RSA密钥</param>/// <param name="isPrivateKey">是否是私钥</param>/// <returns>Pem密钥</returns>public static string RsaKeyToPem(string RSAKey, bool isPrivateKey){string pemKey = string.Empty;var rsa = new RSACryptoServiceProvider();rsa.FromXmlString(RSAKey);RSAParameters rsaPara = new RSAParameters();RsaKeyParameters key = null;//RSA私钥if (isPrivateKey){rsaPara = rsa.ExportParameters(true);key = new RsaPrivateCrtKeyParameters(new BigInteger(1, rsaPara.Modulus), new BigInteger(1, rsaPara.Exponent),new BigInteger(1, rsaPara.D),new BigInteger(1, rsaPara.P), new BigInteger(1, rsaPara.Q), new BigInteger(1, rsaPara.DP),new BigInteger(1, rsaPara.DQ),new BigInteger(1, rsaPara.InverseQ));}//RSA公钥else{rsaPara = rsa.ExportParameters(false);key = new RsaKeyParameters(false,new BigInteger(1, rsaPara.Modulus),new BigInteger(1, rsaPara.Exponent));}using (TextWriter sw = new StringWriter()){var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);pemWriter.WriteObject(key);pemWriter.Writer.Flush();pemKey = sw.ToString();}return pemKey;}/// <summary>/// Pem密钥转RSA密钥/// </summary>/// <param name="pemKey">Pem密钥</param>/// <param name="isPrivateKey">是否是私钥</param>/// <returns>RSA密钥</returns>public static string PemToRsaKey(string pemKey, bool isPrivateKey = false){string rsaKey = string.Empty;object pemObject = null;RSAParameters rsaPara = new RSAParameters();using (StringReader sReader = new StringReader(pemKey)){var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sReader);pemObject = pemReader.ReadObject();}//RSA私钥if (isPrivateKey){RsaPrivateCrtKeyParameters key =(RsaPrivateCrtKeyParameters)((AsymmetricCipherKeyPair)pemObject).Private;rsaPara = new RSAParameters{Modulus = key.Modulus.ToByteArrayUnsigned(),Exponent = key.PublicExponent.ToByteArrayUnsigned(),D = key.Exponent.ToByteArrayUnsigned(),P = key.P.ToByteArrayUnsigned(),Q = key.Q.ToByteArrayUnsigned(),DP = key.DP.ToByteArrayUnsigned(),DQ = key.DQ.ToByteArrayUnsigned(),InverseQ = key.QInv.ToByteArrayUnsigned(),};}//RSA公钥else{RsaKeyParameters key = (RsaKeyParameters)pemObject;rsaPara = new RSAParameters{Modulus = key.Modulus.ToByteArrayUnsigned(),Exponent = key.Exponent.ToByteArrayUnsigned(),};}RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();rsa.ImportParameters(rsaPara);using (StringWriter sw = new StringWriter()){sw.Write(rsa.ToXmlString(isPrivateKey ? true : false));rsaKey = sw.ToString();}return rsaKey;}/// <summary>    /// RSA私钥格式转换,java->.net    /// </summary>    /// <param name="privateKey">java生成的RSA私钥</param>    /// <returns></returns>   public static string RsaPrivateKeyJava2DotNet(string privateKey){RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));}/// <summary>    /// RSA私钥格式转换,.net->java    /// </summary>    /// <param name="privateKey">.net生成的私钥</param>    /// <returns></returns>   public static string RsaPrivateKeyDotNet2Java(string privateKey){XmlDocument doc = new XmlDocument();doc.LoadXml(privateKey);if (doc.DocumentElement == null){return null;}BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));BigInteger exp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));BigInteger d = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));BigInteger q = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));BigInteger dp = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));BigInteger dq = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();return Convert.ToBase64String(serializedPrivateBytes);}/// <summary>    /// RSA公钥格式转换,java->.net    /// </summary>    /// <param name="publicKey">java生成的公钥</param>    /// <returns></returns>    public static string RsaPublicKeyJava2DotNet(string publicKey){RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKey));return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent></RSAKeyValue>",Convert.ToBase64String(publicKeyParam.Modulus.ToByteArrayUnsigned()),Convert.ToBase64String(publicKeyParam.Exponent.ToByteArrayUnsigned()));}/// <summary>    /// RSA公钥格式转换,.net->java    /// </summary>    /// <param name="publicKey">.net生成的公钥</param>    /// <returns></returns>   public static string RsaPublicKeyDotNet2Java(string publicKey){XmlDocument doc = new XmlDocument();doc.LoadXml(publicKey);if (doc.DocumentElement == null){return null;}BigInteger m = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));BigInteger p = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));RsaKeyParameters pub = new RsaKeyParameters(false, m, p);SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pub);byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();return Convert.ToBase64String(serializedPublicBytes);}}
}

RsaHelper

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;namespace RSAStu05
{public class RsaHelper{/// <summary>/// 生成密钥/// <param name="privateKey">私钥</param>/// <param name="publicKey">公钥</param>/// <param name="keySize">密钥长度:512,1024,2048,4096,8192</param>/// </summary>public static void Generator(out string privateKey, out string publicKey, int keySize = 1024){RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize);privateKey = rsa.ToXmlString(true); //将RSA算法的私钥导出到字符串PrivateKey中 参数为true表示导出私钥 true 表示同时包含 RSA 公钥和私钥;false 表示仅包含公钥。publicKey = rsa.ToXmlString(false); //将RSA算法的公钥导出到字符串PublicKey中 参数为false表示不导出私钥 true 表示同时包含 RSA 公钥和私钥;false 表示仅包含公钥。}/// <summary>/// RSA加密 将公钥导入到RSA对象中,准备加密/// </summary>/// <param name="publicKey">公钥</param>/// <param name="encryptstring">待加密的字符串</param>public static string RsaEncrypt(string publicKey, string encryptstring){using (var rsaProvider = new RSACryptoServiceProvider()){var inputBytes = Encoding.UTF8.GetBytes(encryptstring);//有含义的字符串转化为字节流rsaProvider.FromXmlString(publicKey);//载入公钥int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度var buffer = new byte[bufferSize];using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream()){while (true){ //分段加密int readSize = inputStream.Read(buffer, 0, bufferSize);if (readSize <= 0){break;}var temp = new byte[readSize];Array.Copy(buffer, 0, temp, 0, readSize);var encryptedBytes = rsaProvider.Encrypt(temp, false);outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);}return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输}}}/// <summary>  /// RSA解密 载入私钥,解密数据  /// </summary>  /// <param name="privateKey">私钥</param>  /// <param name="decryptstring">待解密的字符串</param>  public static string RsaDecrypt(string privateKey, string decryptstring){using (var rsaProvider = new RSACryptoServiceProvider()){rsaProvider.FromXmlString(privateKey); //载入私钥  var encryptedBytes = Convert.FromBase64String(decryptstring); //将传入的字符串转化为字节流  //var outputStream = new MemoryStream(encryptedBytes);var bufferSize = rsaProvider.KeySize / 8;var buffer = new byte[bufferSize];using (MemoryStream inputStream = new MemoryStream(encryptedBytes), outputStream = new MemoryStream()){while (true){int readSize = inputStream.Read(buffer, 0, bufferSize);if (readSize <= 0){break;}var temp = new byte[readSize];Array.Copy(buffer, 0, temp, 0, readSize);var decryptedBytes = rsaProvider.Decrypt(temp, false);outputStream.Write(decryptedBytes, 0, decryptedBytes.Length);}return Encoding.UTF8.GetString(outputStream.ToArray()); //转化为字符串  }}}/// <summary>/// RSA私钥加密/// </summary>/// <param name="privateKey">私钥</param>/// <param name="encryptstring">待加密的字符串</param>public static string RsaPrivateEncrypt(string privateKey, string encryptstring){var rsaProvider = new RSACryptoServiceProvider();rsaProvider.FromXmlString(privateKey);//载入私钥var inputBytes = Convert.FromBase64String(encryptstring);//有含义的字符串转化为字节流int bufferSize = (rsaProvider.KeySize / 8) - 11;//单块最大长度var buffer = new byte[bufferSize];using (MemoryStream inputStream = new MemoryStream(inputBytes), outputStream = new MemoryStream()){while (true){//分段加密int readSize = inputStream.Read(buffer, 0, bufferSize);if (readSize <= 0){break;}var temp = new byte[readSize];Array.Copy(buffer, 0, temp, 0, readSize);var encryptedBytes = RsaPrivateEncrypt(privateKey, temp);outputStream.Write(encryptedBytes, 0, encryptedBytes.Length);}return Convert.ToBase64String(outputStream.ToArray());//转化为字节流方便传输}}/// <summary>  /// RSA公钥解密/// </summary>  /// <param name="publicKey">公钥</param>  /// <param name="decryptstring">待解密的字符串</param>  public static string RsaPublicDecrypt(string publicKey, string decryptstring){var rsaProvider = new RSACryptoServiceProvider();rsaProvider.FromXmlString(publicKey); //载入私钥  var encryptedBytes = Convert.FromBase64String(decryptstring); //将传入的字符串转化为字节流  var bufferSize = rsaProvider.KeySize / 8;var buffer = new byte[bufferSize];using (MemoryStream inputStream = new MemoryStream(encryptedBytes), outputStream = new MemoryStream()){while (true){int readSize = inputStream.Read(buffer, 0, bufferSize);if (readSize <= 0){break;}var temp = new byte[readSize];Array.Copy(buffer, 0, temp, 0, readSize);var decryptedBytes = decryptByPublicKey(publicKey, temp);outputStream.Write(decryptedBytes, 0, decryptedBytes.Length);}return Convert.ToBase64String(outputStream.ToArray());}}/// <summary>/// 私钥加密/// 这个方法只能加密 私钥长度/8 -11 个字符,分段加密的代码要自己处理了。/// </summary>/// <param name="privateKey">密钥</param>/// <param name="data">要加密的数据</param>/// <returns></returns>public static byte[] RsaPrivateEncrypt(string privateKey, byte[] data){string xmlPrivateKey = privateKey;//加载私钥  RSACryptoServiceProvider privateRsa = new RSACryptoServiceProvider();privateRsa.FromXmlString(xmlPrivateKey);//转换密钥  AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetKeyPair(privateRsa);//IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致       IBufferedCipher c = CipherUtilities.GetCipher("RSA");c.Init(true, keyPair.Private); //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 byte[] DataToEncrypt = data;byte[] outBytes = c.DoFinal(DataToEncrypt);//加密  return outBytes;}/// <summary>/// 用公钥解密/// 这个方法只能加密 私钥长度/8 -11 个字符,分段加密的代码要自己处理了。/// </summary>/// <param name="data"></param>/// <param name="key"></param>/// <returns></returns>public static byte[] decryptByPublicKey(string publicKey, byte[] data){string xmlPublicKey = publicKey;RSACryptoServiceProvider publicRsa = new RSACryptoServiceProvider();publicRsa.FromXmlString(xmlPublicKey);AsymmetricKeyParameter keyPair = DotNetUtilities.GetRsaPublicKey(publicRsa);//转换密钥  // AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(publicRsa);//IBufferedCipher c = CipherUtilities.GetCipher("RSA/ECB/PKCS1Padding");// 参数与Java中加密解密的参数一致       IBufferedCipher c = CipherUtilities.GetCipher("RSA");c.Init(false, keyPair); //第一个参数为true表示加密,为false表示解密;第二个参数表示密钥 byte[] DataToEncrypt = data;byte[] outBytes = c.DoFinal(DataToEncrypt);//解密  return outBytes;}}
}

测试

using System;namespace RSAStu05
{internal class Program{static void Main(string[] args){string publicKey;string privateKey;RsaHelper.Generator(out privateKey, out publicKey);//java的密钥string javaPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCM/ty6yZzpK//t/fRJhNe8U6POQxb50mPfxnKP44Tdlyn9mcntT67CT0gV+M+2wQwZwPTswSCGG6DIBiaII2+WnXlbhbU0S2CM5az+2iRcNC6hBP6vUOmVAkKWF/ZPOE2Jjuf5Qk1WaTqq1fK7PKPt8w1eSCi0HGFWeNZKjGR9JQIDAQAB";//java的私钥string javePrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIz+3LrJnOkr/+399EmE17xTo85DFvnSY9/Gco/jhN2XKf2Zye1PrsJPSBX4z7bBDBnA9OzBIIYboMgGJogjb5adeVuFtTRLYIzlrP7aJFw0LqEE/q9Q6ZUCQpYX9k84TYmO5/lCTVZpOqrV8rs8o+3zDV5IKLQcYVZ41kqMZH0lAgMBAAECgYAlSFEynRQ+PfG/Szs444UuWcmDRY9CQQVCy1VIwgdElu+2DN/tvfe+jrtHgBLgxtw9xR2eqxTAEXcq3SF8Ny6OtCg3RGoj0lbvJiJ6TwAGRurCw4ltPt2A8OOFhax1lwZstaLVNItMawKw7hfD4Zj0bx/uXsoqZgWj5liDPticgwJBAJUpWENPnTit3YOqUPw1ZcxoxU4aKSiWbDGnKhtGZkS62+iNdb3z9BIk2y83mklpnGqPEq9Blgw38kk1IzH1TxMCQQDx/C/zndFyZdiav/AXpQlu5moHPMr+ODPWNNmtZ0bvL3DLKn+CERaNfZ5MsJEXFUTC3IlZtoF4zVZypW+36rHnAkARjEGj+ZPHfTzYJotMgIOvXowHujApZDjqRn4/ozKY11rTqwC1DiQilk9q6KGwDUqnhpluIMskONi6IBQ55mAdAkEAtTKz7WY1mcXtpiMnc20fXS2oI3dAQZBwMGwuu4vkL+KEQX23MPv+uUBhMufcHT7N2GQvbUAePwjzPLHor/1L7QJAISilTN2cCWYj1TRO2s4+pAzdGXlIg8fQF7xa1J0qIoXM+j2tmhda597O/4b0+zHEM7x9KblrjhsxlLp6efzzqQ==";//转化为C#密钥publicKey = CryptoHelper.RsaPublicKeyJava2DotNet(javaPublicKey);//转化为C#私钥privateKey = CryptoHelper.RsaPrivateKeyJava2DotNet(javePrivateKey);Console.WriteLine("公钥加密私钥解密");var data = "待加密的文字内容";var jiami = RsaHelper.RsaEncrypt(publicKey, data);Console.WriteLine(jiami);var jiemi = RsaHelper.RsaDecrypt(privateKey, jiami);Console.WriteLine(jiemi);Console.WriteLine("私钥加密公钥解密");data = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(data));Console.WriteLine(data);jiami = RsaHelper.RsaPrivateEncrypt(privateKey, data);Console.WriteLine(jiami);jiemi = RsaHelper.RsaPublicDecrypt(publicKey, jiami);Console.WriteLine(jiemi);}}
}

C#本身自己无论用私钥加密公钥解密还是公钥加密私钥解密都是可以的
接入java代码,创建maven项目,引入一个maven包

<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.15</version>
</dependency>

App.java

package com.wujialiang.test03;import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;/*** Hello world!**/
public class App {/*** RSA最大加密明文大小*/private static final int MAX_ENCRYPT_BLOCK = 117;/*** RSA最大解密密文大小*/private static final int MAX_DECRYPT_BLOCK = 128;/*** 获取密钥对** @return 密钥对*/public static KeyPair getKeyPair() throws Exception {KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");generator.initialize(1024);return generator.generateKeyPair();}/*** 获取私钥** @param privateKey 私钥字符串* @return*/public static PrivateKey getPrivateKey(String privateKey) throws Exception {KeyFactory keyFactory = KeyFactory.getInstance("RSA");byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);return keyFactory.generatePrivate(keySpec);}/*** 获取公钥** @param publicKey 公钥字符串* @return*/public static PublicKey getPublicKey(String publicKey) throws Exception {KeyFactory keyFactory = KeyFactory.getInstance("RSA");byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);return keyFactory.generatePublic(keySpec);}/*** RSA加密** @param data      待加密数据* @param publicKey 公钥* @return*/public static String encrypt(String data, PublicKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);int inputLen = data.getBytes().length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offset = 0;byte[] cache;int i = 0;// 对数据分段加密while (inputLen - offset > 0) {if (inputLen - offset > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);}out.write(cache, 0, cache.length);i++;offset = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串// 加密后的字符串return new String(Base64.encodeBase64String(encryptedData));}/*** RSA加密** @param data      待加密数据* @param publicKey 公钥* @return*/public static String encrypt(String data, PrivateKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);int inputLen = data.getBytes().length;ByteArrayOutputStream out = new ByteArrayOutputStream();int offset = 0;byte[] cache;int i = 0;// 对数据分段加密while (inputLen - offset > 0) {if (inputLen - offset > MAX_ENCRYPT_BLOCK) {cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);} else {cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);}out.write(cache, 0, cache.length);i++;offset = i * MAX_ENCRYPT_BLOCK;}byte[] encryptedData = out.toByteArray();out.close();// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串// 加密后的字符串return new String(Base64.encodeBase64String(encryptedData));}/*** RSA解密** @param data       待解密数据* @param privateKey 私钥* @return*/public static String decrypt(String data, PrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] dataBytes = Base64.decodeBase64(data);int inputLen = dataBytes.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(dataBytes, offset, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(dataBytes, 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, "UTF-8");}/*** RSA解密** @param data       待解密数据* @param privateKey 私钥* @return*/public static String decrypt(String data, PublicKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] dataBytes = Base64.decodeBase64(data);int inputLen = dataBytes.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(dataBytes, offset, MAX_DECRYPT_BLOCK);} else {cache = cipher.doFinal(dataBytes, 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, "UTF-8");}/*** 签名** @param data       待签名数据* @param privateKey 私钥* @return 签名*/public static String sign(String data, PrivateKey privateKey) throws Exception {byte[] keyBytes = privateKey.getEncoded();PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PrivateKey key = keyFactory.generatePrivate(keySpec);Signature signature = Signature.getInstance("MD5withRSA");signature.initSign(key);signature.update(data.getBytes());return new String(Base64.encodeBase64(signature.sign()));}/*** 验签** @param srcData   原始字符串* @param publicKey 公钥* @param sign      签名* @return 是否验签通过*/public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {byte[] keyBytes = publicKey.getEncoded();X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance("RSA");PublicKey key = keyFactory.generatePublic(keySpec);Signature signature = Signature.getInstance("MD5withRSA");signature.initVerify(key);signature.update(srcData.getBytes());return signature.verify(Base64.decodeBase64(sign.getBytes()));}public static void main(String[] args) throws Exception {TestSimple();}public static void TestSimple() {try {// 生成密钥对KeyPair keyPair = getKeyPair();String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));//java的密钥publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCM/ty6yZzpK//t/fRJhNe8U6POQxb50mPfxnKP44Tdlyn9mcntT67CT0gV+M+2wQwZwPTswSCGG6DIBiaII2+WnXlbhbU0S2CM5az+2iRcNC6hBP6vUOmVAkKWF/ZPOE2Jjuf5Qk1WaTqq1fK7PKPt8w1eSCi0HGFWeNZKjGR9JQIDAQAB";//java的私钥privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIz+3LrJnOkr/+399EmE17xTo85DFvnSY9/Gco/jhN2XKf2Zye1PrsJPSBX4z7bBDBnA9OzBIIYboMgGJogjb5adeVuFtTRLYIzlrP7aJFw0LqEE/q9Q6ZUCQpYX9k84TYmO5/lCTVZpOqrV8rs8o+3zDV5IKLQcYVZ41kqMZH0lAgMBAAECgYAlSFEynRQ+PfG/Szs444UuWcmDRY9CQQVCy1VIwgdElu+2DN/tvfe+jrtHgBLgxtw9xR2eqxTAEXcq3SF8Ny6OtCg3RGoj0lbvJiJ6TwAGRurCw4ltPt2A8OOFhax1lwZstaLVNItMawKw7hfD4Zj0bx/uXsoqZgWj5liDPticgwJBAJUpWENPnTit3YOqUPw1ZcxoxU4aKSiWbDGnKhtGZkS62+iNdb3z9BIk2y83mklpnGqPEq9Blgw38kk1IzH1TxMCQQDx/C/zndFyZdiav/AXpQlu5moHPMr+ODPWNNmtZ0bvL3DLKn+CERaNfZ5MsJEXFUTC3IlZtoF4zVZypW+36rHnAkARjEGj+ZPHfTzYJotMgIOvXowHujApZDjqRn4/ozKY11rTqwC1DiQilk9q6KGwDUqnhpluIMskONi6IBQ55mAdAkEAtTKz7WY1mcXtpiMnc20fXS2oI3dAQZBwMGwuu4vkL+KEQX23MPv+uUBhMufcHT7N2GQvbUAePwjzPLHor/1L7QJAISilTN2cCWYj1TRO2s4+pAzdGXlIg8fQF7xa1J0qIoXM+j2tmhda597O/4b0+zHEM7x9KblrjhsxlLp6efzzqQ==";System.out.println("私钥:" + privateKey);System.out.println("公钥:" + publicKey);// RSA加密String data = "待加密的文字内容";data =  new String(Base64.encodeBase64(data.getBytes()), "utf-8");System.out.println(data);String encryptData = encrypt(data, getPublicKey(publicKey));System.out.println("加密后内容:" + encryptData);// RSA解密String decryptData = decrypt(encryptData, getPrivateKey(privateKey));System.out.println("解密后内容:" + decryptData);// RSA签名String sign = sign(data, getPrivateKey(privateKey));// RSA验签boolean result = verify(data, getPublicKey(publicKey), sign);System.out.print("验签结果:" + result);System.out.println("私钥解密,公钥解密");encryptData = encrypt(data,getPrivateKey(privateKey));System.out.println("加密后内容:" + encryptData);// RSA解密//encryptData ="o7NYi5WkOB2mqEDW5SOPOIyLj03MngafRxYBFbDQNtNhQd+i8DVvFFFJ9yExVN7ccUtcLkdr9XQRDUfeuVjXVlpGDV7OM5ifs6emlFn/7eFDJh1b7t+P2aLvlRdyLfY1xis6yiEFWMFrQxSwBfnt/GYmK8dZf7u2NVjuzIlqZAs=";decryptData = decrypt(encryptData, getPublicKey(publicKey));System.out.println("解密后内容:" + decryptData);} catch (Exception e) {e.printStackTrace();System.out.print("加解密异常");}}
}

java自己也一样无论用私钥加密公钥解密还是公钥加密私钥解密都是可以的,java和C#可以互通的是公钥加密私钥解密,但是私钥加密公钥解密不行,因为这个问题没法彻底解决还是没法使用,又继续百度查找,最终找到了下面的解决方案

使用BouncyCastle

C#需要安装一下BouncyCastle.Cryptography
在这里插入图片描述
RSAHelper

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System;
using System.Collections.Generic;
using System.Text;namespace RSAStu06
{public class RSAHelper{private static Encoding Encoding_UTF8 = Encoding.UTF8;/// <summary>/// KEY 结构体/// </summary>public struct RSAKEY{/// <summary>/// 公钥/// </summary>public string PublicKey { get; set; }/// <summary>/// 私钥/// </summary>public string PrivateKey { get; set; }}public RSAKEY GetKey(){//RSA密钥对的构造器RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();//RSA密钥构造器的参数RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(Org.BouncyCastle.Math.BigInteger.ValueOf(3),new Org.BouncyCastle.Security.SecureRandom(),1024,   //密钥长度25);//用参数初始化密钥构造器keyGenerator.Init(param);//产生密钥对AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();//获取公钥和密钥AsymmetricKeyParameter publicKey = keyPair.Public;AsymmetricKeyParameter privateKey = keyPair.Private;SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");RSAKEY item = new RSAKEY(){PublicKey = Convert.ToBase64String(publicInfoByte),PrivateKey = Convert.ToBase64String(privateInfoByte)};return item;}private AsymmetricKeyParameter GetPublicKeyParameter(string keyBase64){keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");byte[] publicInfoByte = Convert.FromBase64String(keyBase64);Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);return pubKey;}private AsymmetricKeyParameter GetPrivateKeyParameter(string keyBase64){keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");byte[] privateInfoByte = Convert.FromBase64String(keyBase64);// Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入// PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);return priKey;}/// <summary>/// 私钥加密/// </summary>/// <param name="data">加密内容</param>/// <param name="privateKey">私钥(Base64后的)</param>/// <returns>返回Base64内容</returns>public string EncryptByPrivateKey(string data, string privateKey){//非对称加密算法,加解密用IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());//加密try{engine.Init(true, GetPrivateKeyParameter(privateKey));byte[] byteData = Encoding_UTF8.GetBytes(data);var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);return Convert.ToBase64String(ResultData);//Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);}catch (Exception ex){throw ex;}}/// <summary>/// 私钥解密/// </summary>/// <param name="data">待解密的内容</param>/// <param name="privateKey">私钥(Base64编码后的)</param>/// <returns>返回明文</returns>public string DecryptByPrivateKey(string data, string privateKey){data = data.Replace("\r", "").Replace("\n", "").Replace(" ", "");//非对称加密算法,加解密用IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());//解密try{engine.Init(false, GetPrivateKeyParameter(privateKey));byte[] byteData = Convert.FromBase64String(data);var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);return Encoding_UTF8.GetString(ResultData);}catch (Exception ex){throw ex;}}/// <summary>/// 公钥加密/// </summary>/// <param name="data">加密内容</param>/// <param name="publicKey">公钥(Base64编码后的)</param>/// <returns>返回Base64内容</returns>public string EncryptByPublicKey(string data, string publicKey){//非对称加密算法,加解密用IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());//加密try{engine.Init(true, GetPublicKeyParameter(publicKey));byte[] byteData = Encoding_UTF8.GetBytes(data);var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);return Convert.ToBase64String(ResultData);}catch (Exception ex){throw ex;}}/// <summary>/// 公钥解密/// </summary>/// <param name="data">待解密的内容</param>/// <param name="publicKey">公钥(Base64编码后的)</param>/// <returns>返回明文</returns>public string DecryptByPublicKey(string data, string publicKey){data = data.Replace("\r", "").Replace("\n", "").Replace(" ", "");//非对称加密算法,加解密用IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());//解密try{engine.Init(false, GetPublicKeyParameter(publicKey));byte[] byteData = Convert.FromBase64String(data);var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);return Encoding_UTF8.GetString(ResultData);}catch (Exception ex){throw ex;}}}
}

测试

using System;namespace RSAStu06
{internal class Program{static void Main(string[] args){RSAHelper rSAHelper = new RSAHelper();var rsaKey = rSAHelper.GetKey();var privateKey = rsaKey.PrivateKey;var publicKey = rsaKey.PublicKey;Console.WriteLine($"公钥:{privateKey}");Console.WriteLine($"私钥:{publicKey}");privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIMc+TaeRUn7A9Uwg1J4R5jBZmvMF1ndhmoRoPZF4obHkKjbZNCjPSnc6QlpT3O5PJ07Y7zyzDJAjr6Xnn8EMCyeER4SgBRUkJwW1KnPI9sojAVWYNtolr3ITf5z+3xgMptnSRBQENaSLWszP/HvelWTsjrcNQ+gJY20bLyb5P3dAgMBAAECgYAY8YYn8exUqsCL6nLRWbilQwXtNCKtIgvUWg45TApQgd7vgO2pE6UrNa/P7o0DAxaZAxdydu6KEOYXNFke6PkQ/js5q7LhnQkUddCQQzjo4ghB9XoUMX3TnocyKcQ8VkC6IlwHgspBeilsgF83UhfOal67Po9diYeEVhB7FVJRsQJBALiw2p/VyDE8+qDJ1rwoYqqC/rAVhEehZyoomm+8lv3y50y619z/LRnsQr594bACHvNYmFc+s+zRN5XJeYQOwJcCQQC1vGpmVZgcNUs/PYnRgBvfAfaENZ+omJcqM9TYAqa/2wD/FGIIGWByhykThYovOciw/8BOX8+7cE300REz+o+rAkBlOVDpj1LkYaZ/n4AYqg3BpIAQZAqW88hGG/Dg0rzyvEG3FSSgVB8U+R9vpjCetdrexqzgDFayscxERSNblHZLAkB9e3ov7JvZpkathM0bNYyI/675/Jif7bQ6dI1bFQGT6SCX/7fshbEdgwuuqf8OuqRC6mQa+XbSoimBh7WMIU5/AkAZVQGb9T2tWn4BQQzxFXAuXTJ4NPLQgP6JfSPGBAMyzbQB9BHOoYsbvXf4Qm7cDqzYoEsvbjCndAmo1DyraC5a";publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDHPk2nkVJ+wPVMINSeEeYwWZrzBdZ3YZqEaD2ReKGx5Co22TQoz0p3OkJaU9zuTydO2O88swyQI6+l55/BDAsnhEeEoAUVJCcFtSpzyPbKIwFVmDbaJa9yE3+c/t8YDKbZ0kQUBDWki1rMz/x73pVk7I63DUPoCWNtGy8m+T93QIDAQAB";var data = "待加密的文字内容";var jiami = rSAHelper.EncryptByPrivateKey(data, privateKey);Console.WriteLine(jiami);var jiemi = rSAHelper.DecryptByPublicKey(jiami, publicKey);Console.WriteLine(jiemi);}}
}

私钥加密公钥解密还是公钥加密私钥解密都是可以的
java代码,创建maven项目,引入maven依赖

<dependency><groupId>commons-codec</groupId><artifactId>commons-codec</artifactId><version>1.15</version>
</dependency>

KeyStore

package com.wujialiang.test04;public class KeyStore {private String publicKey;private String privateKey;public String getPublicKey() {return publicKey;}public void setPublicKey(String publicKey) {this.publicKey = publicKey;}public String getPrivateKey() {return privateKey;}public void setPrivateKey(String privateKey) {this.privateKey = privateKey;}
}

RSAUtil

package com.wujialiang.test04;import org.apache.commons.codec.binary.Base64;import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;/*** RSA加解密工具<br>*/
public class RSAUtil {public static String RSA_ALGORITHM = "RSA";public static String UTF8 = "UTF-8";/*** 创建公钥私钥*/public static KeyStore createKeys() throws Exception {KeyPairGenerator keyPairGeno = KeyPairGenerator.getInstance(RSA_ALGORITHM);keyPairGeno.initialize(1024);KeyPair keyPair = keyPairGeno.generateKeyPair();RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();KeyStore keyStore = new KeyStore();keyStore.setPublicKey(Base64.encodeBase64String(publicKey.getEncoded()));keyStore.setPrivateKey(Base64.encodeBase64String(privateKey.getEncoded()));return keyStore;}/*** 获取公钥对象*/public static RSAPublicKey getPublicKey(byte[] pubKeyData) throws Exception {X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pubKeyData);KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);return (RSAPublicKey) keyFactory.generatePublic(keySpec);}/*** 获取公钥对象*/public static RSAPublicKey getPublicKey(String pubKey) throws Exception {return getPublicKey(Base64.decodeBase64(pubKey));}/*** 获取私钥对象*/public static RSAPrivateKey getPrivateKey(String priKey) throws Exception {return getPrivateKey(Base64.decodeBase64(priKey));}/*** 通过私钥byte[]将公钥还原,适用于RSA算法*/public static RSAPrivateKey getPrivateKey(byte[] keyBytes) throws Exception {PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);}public static String encryptByPublicKey(String data, String publicKey) throws Exception {return encryptByPublicKey(data, getPublicKey(publicKey));}/*** 公钥加密*/public static String encryptByPublicKey(String data, RSAPublicKey publicKey) throws Exception {Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] bytes = cipher.doFinal(data.getBytes(UTF8));return Base64.encodeBase64String(bytes);}public static String decryptByPublicKey(String data, String rsaPublicKey) throws Exception {return decryptByPublicKey(data, getPublicKey(rsaPublicKey));}/*** 公钥解密*/public static String decryptByPublicKey(String data, RSAPublicKey rsaPublicKey) throws Exception {Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, rsaPublicKey);byte[] inputData = Base64.decodeBase64(data);byte[] bytes = cipher.doFinal(inputData);return new String(bytes, UTF8);}public static String encryptByPrivateKey(String data, String privateKey) throws Exception {return encryptByPrivateKey(data, getPrivateKey(privateKey));}/*** 私钥加密*/public static String encryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, privateKey);byte[] bytes = cipher.doFinal(data.getBytes(UTF8));return Base64.encodeBase64String(bytes);}public static String decryptByPrivateKey(String data, String privateKey) throws Exception {return decryptByPrivateKey(data, getPrivateKey(privateKey));}/*** 私钥解密*/public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey) throws Exception {Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] inputData = Base64.decodeBase64(data);byte[] bytes = cipher.doFinal(inputData);return new String(bytes, UTF8);}
}

测试

package com.wujialiang.test04;/*** Hello world!**/
public class App {public static void main(String[] args) throws Exception {KeyStore keyStore = RSAUtil.createKeys();String privateKey = keyStore.getPrivateKey();String publicKey = keyStore.getPublicKey();privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIMc+TaeRUn7A9Uwg1J4R5jBZmvMF1ndhmoRoPZF4obHkKjbZNCjPSnc6QlpT3O5PJ07Y7zyzDJAjr6Xnn8EMCyeER4SgBRUkJwW1KnPI9sojAVWYNtolr3ITf5z+3xgMptnSRBQENaSLWszP/HvelWTsjrcNQ+gJY20bLyb5P3dAgMBAAECgYAY8YYn8exUqsCL6nLRWbilQwXtNCKtIgvUWg45TApQgd7vgO2pE6UrNa/P7o0DAxaZAxdydu6KEOYXNFke6PkQ/js5q7LhnQkUddCQQzjo4ghB9XoUMX3TnocyKcQ8VkC6IlwHgspBeilsgF83UhfOal67Po9diYeEVhB7FVJRsQJBALiw2p/VyDE8+qDJ1rwoYqqC/rAVhEehZyoomm+8lv3y50y619z/LRnsQr594bACHvNYmFc+s+zRN5XJeYQOwJcCQQC1vGpmVZgcNUs/PYnRgBvfAfaENZ+omJcqM9TYAqa/2wD/FGIIGWByhykThYovOciw/8BOX8+7cE300REz+o+rAkBlOVDpj1LkYaZ/n4AYqg3BpIAQZAqW88hGG/Dg0rzyvEG3FSSgVB8U+R9vpjCetdrexqzgDFayscxERSNblHZLAkB9e3ov7JvZpkathM0bNYyI/675/Jif7bQ6dI1bFQGT6SCX/7fshbEdgwuuqf8OuqRC6mQa+XbSoimBh7WMIU5/AkAZVQGb9T2tWn4BQQzxFXAuXTJ4NPLQgP6JfSPGBAMyzbQB9BHOoYsbvXf4Qm7cDqzYoEsvbjCndAmo1DyraC5a";publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDHPk2nkVJ+wPVMINSeEeYwWZrzBdZ3YZqEaD2ReKGx5Co22TQoz0p3OkJaU9zuTydO2O88swyQI6+l55/BDAsnhEeEoAUVJCcFtSpzyPbKIwFVmDbaJa9yE3+c/t8YDKbZ0kQUBDWki1rMz/x73pVk7I63DUPoCWNtGy8m+T93QIDAQAB";System.out.println("私钥:" + privateKey);System.out.println("公钥:" + publicKey);String data = "待加密的文字内容";String jiami = RSAUtil.encryptByPrivateKey(data, privateKey);System.out.println("加密:" + jiami);String jiemi = RSAUtil.decryptByPublicKey(jiami, publicKey);System.out.println("解密:" + jiemi);}
}

如何java和C#的密钥是一样的,他们是可以相互调用的,RSA C#和java语言的之间的加密解决也就解决了

参考

https://www.cnblogs.com/zhaoshujie/p/14666795.html
https://www.jianshu.com/p/c93a993f8997

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/129720.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

LeetCode(力扣)491. 递增子序列Python

LeetCode491. 递增子序列 题目链接代码 题目链接 https://leetcode.cn/problems/non-decreasing-subsequences/ 代码 class Solution:def backtracking(self, nums, index, result, path):if len(path) > 1:result.append(path[:])uset set()for i in range(index, len…

分类预测 | Matlab实现基于LFDA-SVM局部费歇尔判别数据降维结合支持向量机的多输入分类预测

分类预测 | Matlab实现基于LFDA-SVM局部费歇尔判别数据降维结合支持向量机的多输入分类预测 目录 分类预测 | Matlab实现基于LFDA-SVM局部费歇尔判别数据降维结合支持向量机的多输入分类预测效果一览基本介绍程序设计参考资料 效果一览 基本介绍 基于局部费歇尔判别数据降维的L…

日常开发小汇总(5)元素跟随鼠标移动(在视口下移动)

<div class"mark"><h1>title</h1><div><p>title 鼠标移动 盒子整体移动</p><p>test</p><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi, porro.</p></div></div>cons…

springboot MongoDB 主从 多数据源

上一篇&#xff0c;我写了关于用一个map管理mongodb多个数据源&#xff08;每个数据源&#xff0c;只有单例&#xff09;的内容。 springboot mongodb 配置多数据源 临到部署到阿里云的测试环境&#xff0c;发现还需要考虑一下主从的问题&#xff0c;阿里云买的数据库&#x…

入门力扣自学笔记279 C++ (题目编号:1123)

1123. 最深叶节点的最近公共祖先 题目&#xff1a; 给你一个有根节点 root 的二叉树&#xff0c;返回它 最深的叶节点的最近公共祖先 。 回想一下&#xff1a; 叶节点 是二叉树中没有子节点的节点树的根节点的 深度 为 0&#xff0c;如果某一节点的深度为 d&#xff0c;那它…

【Flutter】引入网络图片时,提示:Failed host lookup: ‘[图片host]‘

在使用 NetworkImage 组件加载外部图片时&#xff0c;提示 Failed host lookup: [图片host] 错误。 排查方向 1、清理缓存 解决方案&#xff1a; 尝试flutter clean清空缓存后重新安装依赖flutter pub get重新构建项目flutter create . 走完上述三个步骤后&#xff0c;再次…

MySql学习笔记11——DBA命令介绍

DBA命令 数据导入 要进入Mysql 创建数据库 create database database_name;使用数据库 use database_name;初始化数据库 source .sql文件地址&#xff0c;不能加双引号&#xff1b;数据导出 要在windows的dos环境下进行 导出数据库 mysqldump database_name > 存放…

Android 文字转语音播放实现

1&#xff0c;TextToSpeech类是android自带的&#xff0c;但是部分设备需要支持TTS需要增加语音库&#xff0c;我使用的是讯飞语音&#xff08;离线的哦&#xff09;。请自行下载并安装讯飞语音APK&#xff0c;然后到系统设置中设置TTS功能默认使用该选项。有自带TTS库的可以省…

《存储IO路径》专题:块设备层多队列blk-mq架构

我们想象一下&#xff0c;你是一个餐厅的厨师&#xff0c;你要准备很多不同的菜肴&#xff0c;而每种菜肴需要不同的食材和烹饪时间。如果每道菜都按照需要的顺序来准备&#xff0c;那么你的工作效率一定会非常低。为了提高效率&#xff0c;你会怎么做呢&#xff1f; 在linux架…

基于SSM的家政服务网站

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

windows 下载安装 mysql

windows 下载安装 mysql 官网地址&#xff1a;https://dev.mysql.com/ 下载地址&#xff1a;https://cdn.mysql.com//Downloads/MySQLInstaller/mysql-installer-community-8.0.34.0.msi 点击 Downloads 点击 MySQL Community (GPL) Downloads 点击 MySQL Installer for Window…

usb学习笔记

框架 usb 驱动是基于usb core 的&#xff0c;设备插上之后&#xff0c;host 层自然会进行识别&#xff0c;设备驱动通过core层的接口操作设备&#xff0c;而不用直接面对usb硬件。对于应用层需要封装成一个usb 的设备。 驱动是基于urb 数据进行操作的。 49 static void usb_mo…

Windows环境下Springboot3+Graalvm+Idea 打包成原生镜像 踩坑

https://github.com/oracle/graal/https://github.com/graalvm/graalvm-ce-builds/releases/对应关系graalvm-ce-java17-windows-amd64-X.X.X.zipnative-image-installable-svm-java17-windows-amd64-X.X.X.jar本人使用:graalvm-ce-java17-windows-amd64-23.0.1.zipnative-imag…

第4章_瑞萨MCU零基础入门系列教程之瑞萨 MCU 源码设计规范

本教程基于韦东山百问网出的 DShanMCU-RA6M5开发板 进行编写&#xff0c;需要的同学可以在这里获取&#xff1a; https://item.taobao.com/item.htm?id728461040949 配套资料获取&#xff1a;https://renesas-docs.100ask.net 瑞萨MCU零基础入门系列教程汇总&#xff1a; ht…

【C++11】{}初始化、std::initializer_list、decltype、STL新增容器

文章目录 1. C11简介2. 统一的列表初始化2.1 &#xff5b;&#xff5d;初始化2.2 std::initializer_list 3. 声明3.1 auto3.2 decltype 4. nullptr5. 范围for循环6. 智能指针7. C11STL中的一些变化8. 演示代码 1. C11简介 在2003年C标准委员会曾经提交了一份技术勘误表(简称TC1…

英语单词(1)

1.void:空的 2.main:主要的 3.class:类 4.system:系统 5.out: 输出 6.print:打印 7.public:公共的,公用的 8.static:静态的,静止的 9.oracle:甲骨文公司 10.eclipse: java编程语言

生存游戏手游推荐,适合长期玩的生存类手游

今天小编为大家带来了生存游戏手游推荐&#xff0c;适合长期玩的生存类手游。许多朋友现在喜欢冒险&#xff0c;想体验荒野生活&#xff0c;但在现实中&#xff0c;由于各种原因可能实现不了。游戏中的生存可以满足玩家对狂野生存的幻想&#xff0c;让现实中未实现的梦想在虚拟…

element-ui switch开关组件二次封装,添加loading效果,点击时调用接口后改变状态

先看效果&#xff1a; element-ui中的switch开关无loading属性&#xff08;在element-plus时加入了&#xff09;&#xff0c;而且点击时开关状态就会切换&#xff0c;这使得在需要调用接口后再改变开关状态变得比较麻烦。 思路&#xff1a;switch开关外包一层div&#xff0c;给…

大学生网页设计制作作业实例代码 (全网最全,建议收藏) HTML+CSS+JS

文章目录 &#x1f4da;web前端期末大作业 (1500套) 集合一、网页介绍二、网页集合 三、作品演示A电影主题B漫画主题C商城主题D家乡主题E旅游主题F餐饮/美食主题G环境主题H游戏主题I 个人主题K体育主题L博客主题M汽车主题N文化主题P美妆主题Q企业主题R教育主题S其他主题 &#…

C++在C语言基础上的优化

目录 一、命名空间 1、命名空间的定义 2、命名空间的使用 二、输入&输出 三、缺省参数 1、缺省参数的概念 2、缺省参数的分类 四、函数重载 五、引用 1.引用的概念 2.引用的特性 3、引用和指针的区别 六、内联函数 七、基于范围的for循环 一、命名空间 命名空…