我正在对一些正在解密数据的代码进行逆向工程,希望我能够将其加密回来并获得与开始时相同的数据,因为这会使这个问题变得太长而且离题。
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
我真的不在乎,但也许它可以帮助回答这个问题。