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

时间:2015-02-18 17:07:31

标签: java php android cryptography rsa

我有一个我一直在使用的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输出是: {"response":"failure","message":false}这意味着openssl_private_decrypt行无法获得正确的解密结果。

由于我的PHP脚本适用于我的iOS代码,除非绝对必要,否则我不想更改它。任何人都可以看到我应该对我的Java代码做什么,以使其与PHP端发生的事情保持一致?

1 个答案:

答案 0 :(得分:3)

您的PHP函数有OPENSSL_PKCS1_OAEP_PADDING,但您的javascript函数正在使用RSA/ECB/PKCS1PADDING

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

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