簡體   English   中英

Java RSA加密

[英]Java RSA Encrypt

我已經在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程序,但它給了我這樣的結果:

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

所以任何人都可以幫助我更正我的Java程序..謝謝

在我看來,您正在對兩種不同的內容進行URL編碼:

  • 在Java中,您正在編碼Base64編碼的字符串,而
  • 在C#中,您正在字節數組上進行操作

這兩種不同方法的結果將不同。 也許您應該在Java部分中對new String( cipherData )進行編碼-或者只是在編碼之前比較兩個byte[]數組?

干杯,

您正在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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM