.NET 对接JAVA 使用Modulus,Exponent RSA 加密

时间:2023-03-08 22:53:19
.NET 对接JAVA 使用Modulus,Exponent RSA 加密

最近有一个工作是需要把数据用RSA发送给Java

虽然一开始标准公钥 net和Java  RSA填充的一些算法不一样 但是后来这个坑也补的差不多了

具体可以参考

http://www.cnblogs.com/dudu/p/csharp-openssl-encrypt-decrypt.html

但是别人给我直接一串10进制的数字
.NET 对接JAVA 使用Modulus,Exponent RSA 加密

然后我又查了一些.net 有一个RSAParameters的类, 我尝试把 modulus 转成Base64 然后生成 RSAParameters对象 然后

使用RSACryptoServiceProvider.ImportParameters 虽然能加密成功 但是加密出来的密文 达到了400多位(正常的能被服务器解析的密文是172位).

之后想自己写一个RSA加密类出来在网上找了一下加密的公式

    BigInteger e = new BigInteger("", );
 BigInteger n = new BigInteger(myModule, );
BigInteger m = new BigInteger(Encoding.Default.GetBytes(""));
var str = m.modPow(e, n).ToString();

这一次加密后的长度是172 但是服务器还是解密失败了

尝试很多种办法时候都不行的时候我开始怀疑我的程序员人生了,因为除了我还有其他部门对接,安卓部门对接是成功的.

被逼无奈我就去找了Java的代码看能不能加密成功

最后用Java的方式加密成功了 Java用到了一个类

Cipher ciphe

然后通过百度去搜.net 有没有这个类.并没有找到相关的文档

最后试了一下谷歌.果然找到了.

原文地址
http://*.com/questions/22825663/cipher-selection-for-sslstream-in-net-4-5
下面贴出我修改过后的代码

                byte[] publicKeyByte = Encoding.Default.GetBytes(Modulus);
byte[] exponentByte = Encoding.Default.GetBytes(Exponent); UTF8Encoding ByteConverter = new UTF8Encoding();
string publicKeyString = System.Text.Encoding.Default.GetString(publicKeyByte);
string exponentString = System.Text.Encoding.Default.GetString(exponentByte); BigInteger publicKeyBI = BigInteger.Parse(publicKeyString);
BigInteger exponentBI = BigInteger.Parse(exponentString); byte[] publicKeyByte2 = publicKeyBI.ToByteArray();
byte[] exponentByte2 = exponentBI.ToByteArray(); if (publicKeyByte2.Length == ) Array.Resize(ref publicKeyByte2, ); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters(); RSAKeyInfo.Modulus = publicKeyByte2.Reverse().ToArray();
RSAKeyInfo.Exponent = exponentByte2.Reverse().ToArray();
RSA.ImportParameters(RSAKeyInfo); byte[] passwordByte = ByteConverter.GetBytes(EncryptString);
    var Ciphertext = Convert.ToBase64String(RSA.Encrypt(passwordByte, false));

完结 撒花 如果这篇文章帮助到你了,希望你能在下方留言告诉我 谢谢