2

我在 C# 程序中使用了 RSA 不对称密钥加密算法(我在下面提到过),我必须通过 java 程序加密数据。我希望我的 java 程序生成与 C# 程序的结果相同的加密密钥。

公钥:

<RSAKeyValue>
<Modulus>zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==</Modulus>
<Exponent>AQAB</Exponent>
</RSAKeyValue>

C#加密程序:

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

 rsa.FromXmlString(PublicKey); // read public key XML defined above

byte[] buffer = rsa.Encrypt(Encoding.UTF8.GetBytes(strToEncrypt), false);

string encryptedStr = HttpUtility.UrlEncode(buffer);// byteConverterGetString;

Java加密程序:

byte[] modulusBytes = Base64.decode("zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==");
byte[] exponentBytes = Base64.decode("AQAB");

BigInteger modulus = new BigInteger(1, modulusBytes );               
BigInteger exponent = new BigInteger(1, exponentBytes);

RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);

KeyFactory fact = KeyFactory.getInstance("RSA");

PublicKey pubKey = fact.generatePublic(rsaPubKey);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

cipher.init(Cipher.ENCRYPT_MODE, pubKey);

byte[] plainBytes = new String("Admin123").getBytes("UTF-8");

byte[] cipherData = cipher.doFinal( plainBytes );

String encryptedString = Base64.encodeBytes(cipherData);

System.out.println(URLEncoder.encode(encryptedString));

我尝试了上面的java程序,但它给了我这样的结果:

o%2Bgw7%2BXhYxA9ltDV5zERsF4DyXgMTc%2Fgx82wRtT1xfR3suY0XBJLadp7bXjmSX7CplDVdoQyH05Jpqgkd%2B1G4A%3D%3D

和 C# 程序生成类似

%23E%03%c2%10)%40E%bf%7b%f9%11%87c0%12q%b9w%ba%2c%98%b4%b1%96%bc%ee%c5_%c9t%1e'%e71 %85%b68t%00%3a%b7%d9%fb%a1%18%ba%10%b4%c3c%e1'*%3b%f6D%e2%cc6%82%80%f2%a6

所以任何人都可以帮我纠正我的java程序..谢谢

4

2 回答 2

1

在我看来,您正在对两种不同的东西进行 URL 编码:

  • 在 Java 中,您正在编码一个 Base64 编码的字符串,而
  • 在 C# 中,您在字节数组上执行此操作

这两种不同方法的结果不会相同。也许您应该new String( cipherData )在 Java 部分进行编码 - 或者只是byte[]在编码之前比较两个数组?

干杯,

于 2012-10-17T07:19:20.010 回答
0

您正在对不同的对象进行 URLencoding,只需尝试以下代码:

byte[] modulusBytes = Base64.decode("zgfXY1oUe4nyndX4qtobP1BMxtJ1/rfKU5csdAcWrSVu6ZaEAX3rL3cWnaSLzX4E1BNjSP9pjge6TH7UoaWqOQ==");
byte[] exponentBytes = Base64.decode("AQAB");

BigInteger modulus = new BigInteger(1, modulusBytes );               
BigInteger exponent = new BigInteger(1, exponentBytes);

RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);

KeyFactory fact = KeyFactory.getInstance("RSA");

PublicKey pubKey = fact.generatePublic(rsaPubKey);

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

cipher.init(Cipher.ENCRYPT_MODE, pubKey);

byte[] plainBytes = new String("Admin123").getBytes("UTF-8");

byte[] cipherData = cipher.doFinal( plainBytes );

String string = new String(cipherData);

System.out.println(URLEncoder.encode(string,"UTF-8"));
于 2014-10-28T16:10:56.827 回答