C# RSA加密与JAVA RSA互通
朕赐你肥皂 2015-02-01 11:18:16 现在一个接口问题,需要客户端(.net)根据RSA生成公钥通过接口发送到服务端(java)
我代码是这样写的:
/// <summary>
/// RSA加密
/// </summary>
/// <param name="str_Plain_Text">需要加密的明文</param>
/// <param name="str_Public_Key">公钥</param>
/// <param name="str_Private_Key">私钥</param>
/// <returns></returns>
public static string RSA_Encrypt(string str_Plain_Text, out string str_Public_Key, out string str_Private_Key)
{
str_Public_Key = "";
str_Private_Key = "";
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToEncrypt = ByteConverter.GetBytes(str_Plain_Text);
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
//OAEP padding is only available on Microsoft Windows XP or later.
byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false);
str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text);
return str_Cypher_Text;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
然后不管怎么调用接口,返回的数据都是空,服务端JAVA那边人说,公钥是正确的就能得到数据,他们本地测试的生成公钥的方法如下:
BASE64Encoder base64Encoder = new BASE64Encoder();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器,密钥大小为2048位
keyPairGen.initialize(2048);
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
Call call=(Call) service.createCall();
call.setTargetEndpointAddress(new URL(SOAP_SERVICE_ENDPOINT));
call.setOperationName("getKey");//调用getKey方法
//传入的公钥
String pk=base64Encoder.encode(publicKey.getEncoded());
各位大神!!!!!!!!请帮忙解决下这个问题,小弟在线等,非常着急