如何在c#中复制java加密

时间:2016-04-25 02:17:11

标签: java c# encryption rsa bouncycastle

我有一个键的公共模数和指数。我正在编写一段测试文本,并获得与我试图复制的java代码不同的结果。

java代码在这里:

RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(modulus, exponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(rsaPublicSpec);
X509EncodedKeySpec encodedPublicKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);
PublicKey publicKey = keyFactory.generatePublic(encodedPublicKeySpec);
Cipher cipher = Cipher.getInstance(“RSA / ECB / PKCS1Padding”);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);    
byte[] encryptedBytes = cipher.doFinal(clearTextString.getBytes());
BASE64Encoder b64 = new BASE64Encoder();
String base64EncodedStr = b64.encode(encryptedBytes);

我现在使用Bouncy Castle在C#中拥有的是:

BigInteger publicModulus = new BigInteger(1, Convert.FromBase64String(publicKeyString));
BigInteger publicExponent = new BigInteger(1,Convert.FromBase64String("AQAB"));
RsaKeyParameters pubParameters = new RsaKeyParameters(false, publicModulus, publicExponent);
IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());
eng.Init(true, pubParameters);
byte[] plaintext = Encoding.UTF8.GetBytes("test data");
byte[] encdata = eng.ProcessBlock(plaintext, 0, plaintext.Length);
Console.WriteLine(Convert.ToBase64String(encdata));

我很困惑为什么java代码获取公钥然后执行X509版本(以及我是否需要在C#实现中执行此操作)。 我还不确定是否需要补偿c#与java的字节顺序。

感谢一些帮助。

1 个答案:

答案 0 :(得分:0)

令人困惑的代码没有做任何事情。另外,一旦我将模数作为base64字符串,实际上并不需要Bouncy Castle。这是有效的。

        var publicKey =
                       "<RSAKeyValue><Modulus>base64modulusgoeshere</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        var sbytes = Encoding.UTF8.GetBytes(s);
        var rsa = new RSACryptoServiceProvider(2048);
        rsa.FromXmlString(publicKey);
        var encdata = rsa.Encrypt(sbytes, false);
        enc = Convert.ToBase64String(encdata);