openssl_public_decrypt返回false但无法获取错误消息

时间:2014-08-09 15:38:02

标签: php openssl

我尝试解码在Android设备上使用RSA私钥编码的字符串(作为某种数字签名)。我认为我的服务器端public key存在问题。

if (openssl_public_decrypt($token, $decrypted, $pubKey) == FALSE)
{
    while ($msg = openssl_error_string())
    {
        echo "ERROR: " . $msg; 
    }

    return;
}

函数openssl_public_decrypt()返回false,但openssl_error_string()不返回任何错误。我怎样才能找出这里出了什么问题?


更新:

这就是我在Android中创建编码值的方法:

public static String Sign(byte[] text, RSAPrivateKey privateKey) throws Exception
{
    // Encode the original data with RSA private key
    byte[] encodedBytes = null;
    try {
        Cipher c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        c.init(Cipher.ENCRYPT_MODE, privateKey);
        encodedBytes = c.doFinal(text);
    } catch (Exception e) {
        Log.e("RSAHelper", "RSA encryption error");
        throw e;
    }

    return Base64.encodeToString(encodedBytes, Base64.DEFAULT);
}

2 个答案:

答案 0 :(得分:0)

  

我尝试解码在Android设备上使用RSA私钥编码的字符串(作为某种数字签名)

如果是数字签名,则填充方案不同。 RSA加密使用类型2填充,而RSA签名使用类型1填充。

由于您认为它是数字签名,因此您应该寻找openssl_public_verify函数(或类似函数)。

答案 1 :(得分:0)

我没有真正找出为什么openssl_error_string()没有返回任何内容,但我可以用未接受的PublicKey

来解决我的问题

由于密钥对是由Android创建的,因此PHP无法直接使用密钥对。需要解决以下问题:

  • 缺少页眉和页脚
  • 错误的换行

// remove existing line breaks
$pubKey = str_replace ("\r\n" , "" , $pubKey);
$pubKey = str_replace ("\r" , "" , $pubKey);
$pubKey = str_replace ("\n" , "" , $pubKey);

// insert line breaks as expexted by PHP function
$pubKey = wordwrap($pubKey, 65, "\n", true);

// add header and footer
$pubKeyWithHeader = "-----BEGIN PUBLIC KEY----- \r\n" . $pubKey 
             . " \r\n-----END PUBLIC KEY-----";

// decode the key
openssl_pkey_get_public($pubKeyWithHeader);
if ($x == FALSE)
{
    echo "error";
    return;
}

// decrypt the message with the public key
if (openssl_public_decrypt($token, $decrypted, $pubKeyWithHeader) == FALSE)
{
    echo "error";
    return;
}

echo $decrypted;
相关问题