openssl_pkcs7_sign 确实以 PEM 格式对数据进行了签名,但您可以只获取 PEM 数据的 base64 块并使用 base64_decode() 将其转换为 DER。
function get_base64($file_name) {
$content = file($file_name, FILE_IGNORE_NEW_LINES);
$base64_data = "";
for ($i=5; $i<sizeof($content); $i++){ // take only the base64 chunk
$base64_data .= $content[$i];
}
return $base64_data;
}
function pem2der($base64_data) {
$der = base64_decode($base64_data);
return $der;
}
if (openssl_pkcs7_sign( // Signs file_in and saves as file_out in PEM format
"file_in", // Input file
"file_out", // Output file (PEM format)
"file://../.pki/company.crt", // Certificate (mycert.pem)
"file://../.pki/company.key", // Private key (mykey.pem)
array(),
PKCS7_NOATTR,
"../.pki/company.cacrt" // Intermediate certificate (mybundle.crt)
)) {
$data = pem2der(get_base64("file_out")); // converts content of file_out to DER format
$out = fopen("file_out", "w") or die("Unable to open file!");
fwrite($out,$data); // output file (DER format)
fclose($out);
echo("File signed successfully!")
}
?>