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.mzph.cn/news/76057.shtml

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

相关文章

人工智能AI 全栈体系(一)

第一章 神经网络是如何实现的 这些年人工智能蓬勃发展&#xff0c;在语音识别、图像识别、自然语言处理等多个领域得到了很好的应用。推动这波人工智能浪潮的无疑是深度学习。所谓的深度学习实际上就是多层神经网络&#xff0c;至少到目前为止&#xff0c;深度学习基本上是用神…

华为Mate60 Pro手机重大突破,资本要做空iPhone?Android开发市场将来会如何?

在9月10日有消息称&#xff0c;在华为的Mate60 Pro手机取得重大突破&#xff0c;其研发的 麒麟9000s芯片的研制&#xff0c; 国际卫星通信技术的应用 等这一系列的重大突破&#xff0c;导致美国的一家对冲基金Satori Fund创始人公开要做空iPhone。 而摩根大通发布报告称&#x…

十二、集合(5)

本章概要 for-in 和迭代器 适配器方法惯用法 本章小结 简单集合分类 for-in和迭代器 到目前为止&#xff0c;for-in 语法主要用于数组&#xff0c;但它也适用于任何 Collection 对象。实际上在使用 ArrayList 时&#xff0c;已经看到了一些使用它的示例&#xff0c;下面是它…

el-form表单中不同数据类型对应的时间格式化和校验规则

1. 在表单中, 当选择不同的数据类型时, 需要在下面选择时间时和数据类型对应上, 通过监听数据类型的变化, 给时间做格式化, 2. 但是当不按顺序选择数据类型后, 再选时间可能会报错, 所以需要在dom更新后, 再清空表单. 3. 校验规则, 结束时间需要大于开始时间, 但是不能选当前的…

排序算法:快速排序(三种排序方式、递归和非递归)

朋友们、伙计们&#xff0c;我们又见面了&#xff0c;本期来给大家解读一下有关排序算法的相关知识点&#xff0c;如果看完之后对你有一定的启发&#xff0c;那么请留下你的三连&#xff0c;祝大家心想事成&#xff01; C 语 言 专 栏&#xff1a;C语言&#xff1a;从入门到精通…

GeoNet: Unsupervised Learning of Dense Depth, Optical Flow and Camera Pose 论文阅读

论文信息 题目&#xff1a;GeoNet: Unsupervised Learning of Dense Depth, Optical Flow and Camera Pose 作者&#xff1a;Zhichao Yin and Jianping Shi 来源&#xff1a;CVPR 时间&#xff1a;2018 Abstract 我们提出了 GeoNet&#xff0c;这是一种联合无监督学习框架&a…

vim常用操作

一、Esc键 & 命令模式 1.撤销&#xff1a;u 恢复撤销&#xff1a;Ctrl r 2.定位 行首&#xff1a;0 行尾&#xff1a;$ 第7行&#xff1a;7G 3.编辑 下行开始插入&#xff1a; o 删除行&#xff1a;dd 复制3行并粘贴&#xff1a;3yy ---> p 复制单词并粘贴&#…

蓝桥杯官网练习题(玩具蛇)

题目描述 本题为填空题&#xff0c;只需要算出结果后&#xff0c;在代码中使用输出语句将所填结果输出即可。 小蓝有一条玩具蛇&#xff0c;一共有 16 节&#xff0c;上面标着数字 1 至 16。每一节都是一个正方形的形状。相邻的两节可以成直线或者成 90 度角。 小蓝还有一个…

时序预测 | MATLAB实现ELM极限学习机时间序列预测未来

时序预测 | MATLAB实现ELM极限学习机时间序列预测未来 目录 时序预测 | MATLAB实现ELM极限学习机时间序列预测未来预测效果基本介绍程序设计参考资料 预测效果 基本介绍 1.MATLAB实现ELM极限学习机时间序列预测未来&#xff1b; 2.运行环境Matlab2018及以上&#xff0c;data为数…

【漏洞复现】H3C路由器信息泄露任意用户登录

漏洞描述 通过访问特地址得到密码可进行登录。 免责声明 技术文章仅供参考&#xff0c;任何个人和组织使用网络应当遵守宪法法律&#xff0c;遵守公共秩序&#xff0c;尊重社会公德&#xff0c;不得利用网络从事危害国家安全、荣誉和利益&#xff0c;未经授权请勿利用文章中…

CASAIM与南京航空航天大学在自动化叶片曲面分析系统开展合作,推动航空航天发动机零部件自动化3D检测进程

近期&#xff0c;CASAIM与南京航空航天大学在自动化叶片曲面分析系统展开深入合作&#xff0c;充分发挥双方在航空航天和智能检测领域优势&#xff0c;共同推动航空航天发动机零部件自动化3D检测进程。 南京航空航天大学创建于1952年10月&#xff0c;是新中国自己创办的第一批…

pyCharm远程DEBUG

第一步&#xff0c;添加一个远程机器的解释器 ssh 远程机器解释器添加&#xff0c; 我本地ssh有配置目标机器。 如果没配置&#xff0c;那就选着new server configuration 新增一个。 interpreter 指定远程机器python&#xff0c; &#xff08;机器上有多个版本python里尤其要…

红队打靶:ConnectTheDots打靶思路详解(vulnhub)

目录 写在开头 第一步&#xff1a;主机发现和端口扫描 第二步&#xff1a;FTP和NFS渗透&#xff08;失败&#xff09; 第三步&#xff1a;web渗透 第四步&#xff1a;jsfuck解码 第五步&#xff1a;再次FTP渗透与莫尔斯电码解码 第六步&#xff1a;vim读取断电swp文件…

批量采集的时间管理与优化

在进行大规模数据采集时&#xff0c;如何合理安排和管理爬取任务的时间成为了每个专业程序员需要面对的挑战。本文将分享一些关于批量采集中时间管理和优化方面的实用技巧&#xff0c;帮助你提升爬虫工作效率。 1. 制定明确目标并设置合适频率 首先要明确自己所需获取数据的范…

Bazzite 发行版 1.0 发布,可让 Linux 游戏机实现 Steam Deck 桌面环境体验

导读近日消息&#xff0c;当下 Steam Deck 掌机的性能已经有所过时&#xff0c;不过许多玩家为了追求原生 SteamOS 体验依然选择购买该掌机&#xff0c;V社此前曾表示&#xff0c;“SteamOS 简化了在手持设备上玩 PC 游戏的过程”&#xff0c;玩家在用 Steam Deck 玩游戏时&…

BCSP-玄子Share-Java框基础_工厂模式/代理模式

三、设计模式 3.1 设计模式简介 软件设计中的三十六计是人们在长期的软件开发中的经验总结是对某些特定问题的经过实践检验的特定解决方法被广泛运用在 Java 框架技术中 3.1.1 设计模式的优点 设计模式是可复用的面向对象软件的基础可以更加简单方便地复用成功的设计和体系…

springcloud-Eureka

1.Eureka注册中心 1.1 简介与依赖导入 1.2 服务注册与发现 启动eureka模块 访问Eureka 将user-service,book-service,borrow-service作为eureka的客户端&#xff0c;先导包。三个导入方式一样。 配置文件&#xff0c;三个模块下都一样配置 然后分别启动三个模块 发现注册…

SpringMvc--CRUD

目录 一.什么是SpringMvc--CRUD 二.前期准备 公共页面跳转(专门用来处理页面跳转) 三.ssm之CRUD后端实现 配置pom.xml 双击mybatis-generator:generate自动生成mapper 编写generatorConfig.xml 项目结构 编写PagerAspect切面类 编写hpjyBiz接口类 编写hpjyBizImpl接…

JavaWeb_LeadNews_Day11-KafkaStream实现实时计算文章分数

JavaWeb_LeadNews_Day11-KafkaStream实现实时计算文章分数 KafkaStream概述案例-统计单词个数SpringBoot集成 实时计算文章分值来源Gitee KafkaStream 概述 Kafka Stream: 提供了对存储与Kafka内的数据进行流式处理和分析的功能特点: Kafka Stream提供了一个非常简单而轻量的…

Pytorch 多卡并行(1)—— 原理简介和 DDP 并行实践

近年来&#xff0c;深度学习模型的规模越来越大&#xff0c;需要处理的数据也越来越多&#xff0c;单卡训练的显存空间和计算效率都越来越难以满足需求。因此&#xff0c;多卡并行训练成为了一个必要的解决方案本文主要介绍使用 Pytorch 的 DistributedDataParallel&#xff08…