【发布时间】:2019-04-07 05:41:54
【问题描述】:
我正在对一些解密数据的代码进行逆向工程,希望能够将其加密回来并获得与 reasons that would make this question too long and off-topic 开始时相同的数据。
public void Test() throws Exception {
String pk_enc = //...
String hashStr_64 = //...
byte[] hashStr_encrypted = Base64.decode(hashStr_64);
X509EncodedKeySpec e = new X509EncodedKeySpec(Base64.decode(pk_enc));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey RSApublicKey = (RSAPublicKey) keyFactory.generatePublic(e);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher.init(2, RSApublicKey); // '2' means decrypt
byte[] hashStr_decrypted = cipher.doFinal(hashStr_encrypted);
String hashStr_result = new String(hashStr_decrypted);
// Now in reverse...
Cipher cipher1 = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
// instantiating a new cipher or using the original one makes no difference
cipher1.init(1, RSApublicKey); // '1' means encrypt
byte[] hashStr_encrypted_reverse = cipher1.doFinal(hashStr_decrypted);
String hashStr_64_reverse = Base64.encode(hashStr_encrypted_reverse);
}
// Now in reverse...之前的所有代码都不能更改,但这并不意味着不能将hashStr_result转换回hashStr_64,对吧?
但是,我之后编写的代码应该可以做到这一点,但它不起作用。
hashStr_encrypted_reverse 与 hashStr_encrypted 不同。为什么会这样,我该如何解决?
另一个表明加密出了问题的迹象是,如果我再次尝试解密会发生什么...
// Decrypt again
Cipher cipher2 = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
cipher2.init(2, RSApublicKey);
byte[] hashStr_decrypted_again = cipher.doFinal(hashStr_encrypted_reverse);
这会抛出:
javax.crypto.BadPaddingException
我真的不在乎,但也许它可以帮助回答这个问题。
【问题讨论】:
-
这不是 RSA 的工作方式。一项操作使用公钥,另一项操作使用私钥。您不能使用公钥进行这两项操作。
-
这是我想过的,但您会看到我们有一个 public 密钥,实际上是 解密 数据。我有限的理解是,使用 RSA 公钥只能加密,不能解密。所以我认为这与我所知道的 RSA 不同(或者肯定可以将其加密回来)。感谢您的提示:我会朝这个方向进行更多研究!
标签: java encryption rsa badpaddingexception