开发者

.NET and Java producing different signature

I have a sample code in java which I am trying to convert to .NET c# platform. This code encrypts a string and add signature to it. Java code using BouncyCastle provider and the code for adding signature follows.

 InputStream in = new FileInputStream(derkeyfilename);
 byte[] privKeyBytes = new byte[in.available()]; 
 in.read(privKeyBytes);
 KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA");
 PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
 private RSAPrivateKey myPrivateKey = (RSAPrivateKey) rsaKeyFac.generatePrivate(encodedKeySpec);

 MessageDigest md = MessageDigest.getInstance("MD5", "BC");
 byte[] digest = md.digest(msg);
 Signature sig = Signature.getInstance("MD5withRSA", "BC");
 sig.initSign(myPrivateKey);
 sig.update(digest);
 byte[] signature = sig.sign();
 byte[] base64 = Base64.encodeBase64(signature);
 String signature = new String(base64);

Can anyone help me开发者_如何学运维 converting this to c#. I tried few samples (BouncyCastle for C#, openssl etc) and all are returning same signature which is different from what java produces. One more thing I found is java uses .der private key which is not supported in C# (as far as I know). I am using .pem key for the same certificate.


As you don't show your C# point, I can only guess what your problem is:

In Java, you are doing a double MD5 hash. Once explicitly in your code, and once implicitly in your Signature object (which is defined as MD5WithRSA, as you can see). Thus you have here

signatureJava = RSA(MD5(MD5(msg)))

If you don't do this first MD5 explicitly on the C# side, you there have:

signatureC# = RSA(MD5(msg))

Obviously these are not the same, unless you have hit a fixpoint of MD5 with your message (very unlikely).

Other than this, are you sure that the C# signature is always the same? As I understand, an RSA signature is (in the modes normally used) not deterministic, since it incorporates some random padding data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜