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

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

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

具体可以参考

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

但是别人给我直接一串10进制的数字

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

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

 

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

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

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

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

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

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

Cipher ciphe

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

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

原文地址
http://stackoverflow.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 == 129) Array.Resize(ref publicKeyByte2, 128);

                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));

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

转载于:https://www.cnblogs.com/wangshisuifeng/p/6251865.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值