Java中的RSA加密/PHP中的解密失败


RSA Encryption in Java / Decryption in PHP Fails

我有一个PHP脚本,我一直在使用它来解密我从iOS加密的会话密钥。加密是在客户端上使用1024位公钥完成的。服务器端的解密是使用相应的私钥完成的。现在我正在尝试为Android编写一种加密方法。不幸的是,解密仍然失败,我看不出有什么问题。

这是Android代码:

public String encryptSessionKeyWithPublicKey(String pemString, byte[] sessionKey) {
    try {
        PublicKey publicKey = getPublicKeyFromPemFormat(pemString);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipherData = cipher.doFinal(sessionKey);
        return Base64.encodeToString(cipherData, Base64.DEFAULT);
    } catch (IOException ioException) {
        Log.e(TAG, "ioException");
    } catch (NoSuchAlgorithmException exNoSuchAlg) {
        Log.e(TAG, "NoSuchAlgorithmException");
    } catch (InvalidKeySpecException exInvalidKeySpec) {
        Log.e(TAG, "InvalidKeySpecException");
    } catch (NoSuchPaddingException exNoSuchPadding) {
        Log.e(TAG, "NoSuchPaddingException");
    } catch (InvalidKeyException exInvalidKey) {
        Log.e(TAG, "InvalidKeyException");
    } catch (IllegalBlockSizeException exIllBlockSize) {
        Log.e(TAG, "IllegalBlockSizeException");
    } catch (BadPaddingException exBadPadding) {
        Log.e(TAG, "BadPaddingException");
    }
    return null;
}
private PublicKey getPublicKeyFromPemFormat(String PEMString)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
{
    AssetManager assetManager = context.getAssets();
    InputStream inputStream = assetManager.open(PEMString);
    BufferedReader pemReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuffer content = new StringBuffer();
    String line = null;
    while ((line = pemReader.readLine()) != null) {
        if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
            while ((line = pemReader.readLine()) != null) {
                if (line.indexOf("-----END PUBLIC KEY") != -1) {
                    break;
                }
                content.append(line.trim());
            }
            break;
        }
    }
    if (line == null) {
        throw new IOException("PUBLIC KEY not found");
    }
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(new X509EncodedKeySpec(Base64.decode(content.toString(), Base64.DEFAULT)));
}

PHP脚本相当简单:

<?php
$passphrase = 'xxxxxxxx'; // just for testing - load from file later
$decrypted_session_key = 'unavailable';
$encrypted_session_key = base64_decode($_POST['encrypted_session_key']);
$fp = fopen('private128.pem', 'r');
if ($fp == null) { 
    $arr = array('response' => 'failure', 'message' => 'private key not readable');
    echo json_encode($arr);
    die();
}
$priv_key = fread($fp, 8192);
fclose($fp);
$res = openssl_get_privatekey($priv_key, $passphrase);
$decr_result = openssl_private_decrypt($encrypted_session_key, $decrypted_session_key, $res, OPENSSL_PKCS1_OAEP_PADDING);
if (!$decr_result) {
    $arr = array('response' => 'failure', 'message' => $decr_result);
    echo json_encode($arr);
    die();
}
// write the decrypted string to a file
$session_key_file = fopen("session_key", "w") or die("Unable to open file!");
fwrite($session_key_file, $decrypted_session_key);
fclose($session_key_file);
$arr = array('response' => 'success', 'message' => 'server confirms receipt of session key');
echo json_encode($arr);
?>

我试图加密的只是16个随机生成的字节。

PHP输出为:CCD_ 1,这意味着CCD_。

由于我的PHP脚本可以与我的iOS代码一起使用,除非绝对必要,否则我不想更改它。有人能看到我应该对我的Java代码做些什么来使它与PHP方面发生的事情保持一致吗?

您的PHP函数有OPENSSL_PKCS1_OAEP_PADDING,但您的java函数使用RSA/ECB/PKCS1PADDING

  1. 将您的PHP解密更改为OPENSSL_PKCS1_PADDING,这似乎与您的java加密相匹配

  1. 将java加密切换为RSA/ECB/OAEPWithSHA-1AndMGF1Padding