I have PHP code that encrypts some plaintext, it looks something like the following
function encryptSecretKeyWithCertificate($plainKey, $certFilePath) {
$certContent = file_get_contents($certFilePath);
if (!$certContent) {
throw new Exception("can't load certificate: $certFilePath");
}
$rsa = PublicKeyLoader::load($certContent)
->withHash('sha256')
->withMGFHash('sha256')
->withPadding(RSA::ENCRYPTION_OAEP);
return rtrim(strtr(base64_encode($rsa->encrypt($plainKey)), '+/', '-_'), '=');
}
I used phpseclib3. It returns a base64urlsafe encoded string. This string will be sent to another application (implemented using java) and is decrypted by the following function.
private static byte[] decryptSecretKey(PrivateKey privKey, byte[] encKey) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
PSource.PSpecified.DEFAULT);
cipher.init(Cipher.DECRYPT_MODE, privKey, oaepParams);
return cipher.doFinal(encKey, 0, encKey.length);
}catch (Exception ex){
ex.printStackTrace();
return null;
}
}
I have verified that both encoding and decoding are done correctly (base64) but trying to decrypt the data throws the following exception.
javax.crypto.BadPaddingException: Decryption error
at java.base/sun.security.rsa.RSAPadding.unpadOAEP(RSAPadding.java:488)
at java.base/sun.security.rsa.RSAPadding.unpad(RSAPadding.java:284)
at java.base/com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:366)
at java.base/com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:400)
at java.base/javax.crypto.Cipher.doFinal(Cipher.java:2303)
at org.example.CryptoUtil.decryptSecretKey(CryptoUtil.java:264)
at org.example.CryptoUtil.symmetricDecryptResponse(CryptoUtil.java:224)
at org.example.Main.main(Main.java:40)
Just for testing I implemented the encryption function in Java (which works) and it looks like this
public static String encryptSecretKeyAsymmetric(byte[] key, PublicKey publicKey) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
final OAEPParameterSpec oaepParams = new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256,
PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, publicKey, oaepParams);
byte[] cipherText = cipher.doFinal(key);
String encodedCipher = doEncode(cipherText);
return encodedCipher;
}
I would appreciate any help. Is it even possible to implement this type of encryption with the RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING transform and the various specs in PHP?