Java RSA加密

时间:2012-10-17 07:12:33

标签: c# java encryption rsa

我在C#程序中使用了RSA Assymetric密钥加密算法(我在下面提到过),我必须通过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程序上面尝试过,但它给我的结果如下:

  

0%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 < / p>

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

2 个答案:

答案 0 :(得分:1)

在我看来,你是URL编码两个不同的东西:

  • 在Java中,您正在编码Base64编码的字符串,而
  • 在C#中你是在一个字节数组
  • 上做的

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

干杯,

答案 1 :(得分:0)

您是编码不同对象的URL,只需尝试以下代码:

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