php - Openssl_pkcs7_sign(): error opening file

889

it's my first time doing signing of cert using openssl. Keep hitting the above error and tried realpath() and appending file:// but still can't get openssl to sign the profile. I don't understand how this works. Any insights would be appreciated.

Edit1: I'm not sure which file is the problematic one. The error messages wasn't specific enough. Is there a way to tell?

Code and screenshots below:

function signProfile()
{
    $filename = "./template.mobileconfig";
    $filename = realpath($filename);
    $outFilename = $filename . ".tmp";
    $pkey = dirname(__FILE__) . "/PteKey.key";
    $pkey = realpath($pkey);
    $certFile = dirname(__FILE__) . "/CertToSign.crt";
    $certFile = realpath($certFile);

    // try signing the plain XML profile
    if (openssl_pkcs7_sign($filename, $outFilename, 'file://'.$certFile, array('file://'.$pkey, ""), array(), 0, "")) 
    {
        // get the data back from the filesystem
        $signedString = file_get_contents($outFilename);
        // trim the fat
        $trimmedString = preg_replace('/(.+\n)+\n/', '', $signedString, 1);
        // convert to binary (DER)
        $decodedString = base64_decode($trimmedString);
        // write the file back to the filesystem (using the filename originally given)
        $fh = fopen($filename, 'w');
        fwrite($fh, $decodedString);
        fclose($fh);
        // delete the temporary file
        unlink($outFilename);
        return TRUE;
    } 
    else
    {
        return FALSE;
    }
}
341

Answer

Solution:

  1. Remove unwanted fields if not used in

    openssl_pkcs7_sign($mobileConfig, $tmpMobileConfig, $certFile, array($pkey, ""), array());

  2. Make sure file paths are correctly supplied.

    require_once('variables.php'); //stores abs path to $tmpMobileConfig/$pteKeyPath/$CertToSignPath
    $prepend = "file://";
    $mobileConfig = realpath("./template.mobileconfig");
    $pkey = $prepend . $pteKeyPath;
    $pkey = str_replace('\\', '/', $pkey);
    $certFile = $prepend . $CertToSignPath;
    $certFile = str_replace('\\', '/', $certFile);
    $isSignedCert = openssl_pkcs7_sign($mobileConfig, $tmpMobileConfig, $certFile, array($pkey, ""), array());
    

People are also looking for solutions to the problem: php - Display data from variables with condition

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.