I'm using PHPSecLib to encrypt my text with RSA:
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
extract($rsa->createKey());
$rsa->loadKey($privatekey);
$ciphertext = $rsa->encrypt($plaintext);
$rsa->loadKey($publickey);
return base64_encode($ciphertext) . ":" . base64_encode($publickey);
I get something like encryptedBased64:publicKeyBased64.
It seems to work and if I try to decrypt using the same method with PHP it works as well. But trying to decrypt with java, gives me java.security.InvalidKeyException: invalid key format. This is the code:
public static String decrypt(byte[] msg, byte[] key)
throws Exception{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key);
PublicKey keys = keyFactory.generatePublic(publicKeySpec);
Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding","BC");
cipher.init(Cipher.DECRYPT_MODE, keys);
return new String(cipher.doFinal(msg));
}
public static void main(String[] args) throws Exception{
String res = "encryptedBased64:publicKeyBased64";
decrypt(Base64.getDecoder().decode(res.split(":")[0]),Base64.getDecoder().decode(res.split(":")[1]));
}
Cannot understand why.