PHP 7.1.12 Released

openssl_pkcs7_sign

(PHP 4 >= 4.0.6, PHP 5, PHP 7)

openssl_pkcs7_signSignieren einer S/MIME message

Beschreibung

bool openssl_pkcs7_sign ( string $infilename , string $outfilename , mixed $signcert , mixed $privkey , array $headers [, int $flags [, string $extracerts ]] )

Die Funktion openssl_pkcs7_sign() signiert die Inhalte der Datei, angegeben durch den Pararmeter infilename. Beim Signieren wird das Zertifikat, angegeben durch signcert, und der dazu gehörige private Schlüssel privkey benutzt.

Parameter-Liste

infilename

outfilename

signcert

privkey

headers

headers ist ein Array aus Headern die den Daten vorangestellt werden, nachdem diese signiert wurden (Für mehr Informationen über das Format dieses Parameters schauen Sie bei der Funktion openssl_pkcs7_encrypt() nach).

flags

Der Parameter flags kann zur Änderung der Ausgabe benutzt werden - siehe PKCS7 Konstanten - falls nicht angegeben ist die Vorgabe PKCS7_DETACHED.

extracerts

Der Parameter extracerts gibt den Namen einer Datei an, die ein oder mehrere extra Zertifikate enthält, die in die Unterschrift mit eingefügt werden. Das kann zum Beispiel als Hilfe für einen Empfänger dienen, das von Ihnen benutzte Zertifikat zu überprüfen.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Beispiele

Beispiel #1 openssl_pkcs7_sign() Beispiel

<?php
// Die Nachricht die Sie unterschreiben möchten, damit der Empfänger sicher
// sein kann, dass diese Nachricht von ihnen stammt.

$data = <<<EOD

Sie haben meine Erlaubnis 10.000 EUR für Essen auszugeben.

Der CEO
EOD;
// Nachricht in einer Datei speichern
$fp fopen("msg.txt""w");
fwrite($fp$data);
fclose($fp);
// verschlüsslen
if (openssl_pkcs7_sign("msg.txt""signed.txt""mycert.pem",
    array(
"file://mycert.pem""mypassphrase"),
    array(
"To" => "joes@example.com"// keyed syntax
          
"From: HQ <ceo@example.com>"// indexed syntax
          
"Subject" => "Eyes only")
    )) {
    
// Nachricht signiert - abschicken!
    
exec(ini_get("sendmail_path") . " < signed.txt");
}
?>

add a note add a note

User Contributed Notes 11 notes

up
2
Maciej_Niemir at ilim dot poznan dot pl
14 years ago
This command doesn't work correctly on WIN32 with IIS. Mails arent interpreted correctly by IIS SMTP Server (and by Outlook too). The reason is that UNIX and WINDOWS interpret the enter to the next line ascii code in a different way.

Below I present an improved code:

<?php

$data
= <<<EOD

Testing 123

This is a test

Test

EOD;

//save the message to a file
$fp = fopen("msg.txt","w");
fwrite($fp,$data);
fclose($fp);

//sign the message using the sender's keys
openssl_pkcs7_sign("msg.txt", "signed.eml", "file://c:/max/cert.pem",
array(
"file://c:/max/priv.pem","your_password"),
array(
"To" => "recipient <recipients@mail.com>",
"From" => "sender <sender@mail.com>",
"Subject" => "Order Notification - Test"),PKCS7_DETACHED,"c:\max\extra_cert.pem");

$file_arry = file("signed.eml");
$file = join ("", $file_arry);
$message = preg_replace("/\r\n|\r|\n/", "\r\n", $file);

$fp = fopen("c:\Inetpub\mailroot\Pickup\signed.eml", "wb");
flock($fp, 2);
fputs($fp, $message);                                                    
flock($fp, 3);
fclose($fp);

?>

Besides, if you want to use the keys created with Windows, you should export them (from IE) to the form of PKCS#12 file (*.pfx).

Install OpenSSLWin32 from
http://www.shininglightpro.com/search.php?searchname=Win32+OpenSSL

execute: openssl.exe

enter the commands:

pkcs12 -in <pfx-file> -nokeys -out <pem-certs-file>

pkcs12 -in <pfx-file> -nocerts -nodes -out <pem-key-file>

Next export from IE Root CA certificate as Base-64 *.cer and rename the file to *.pem

And that's all!
up
1
yurchenko dot anton at gmail dot com
8 years ago
I also spent hours when trying to find the reason of error:
"error getting private key".

Sometimes this error appeared, sometimes not.

My solution is using the realpath() for every parameter of openssl_pkcs7_sign. In my case the code looks like:

<?php
$Certif_path
= 'certificate/mycertificate.pem';

$clearfile = "certificate/random_name";
$encfile = $clearfile . ".enc";
$clearfile = $clearfile . ".txt";

// ----
// -- fill $clearfile with the mail to be signed ...
// ----

openssl_pkcs7_sign(realpath($clearfile),
                          
realpath('.').'/'.$encfile, // because $encfile does not exist yet we cannot use realpath($encfile);
                          
'file://'.realpath($Certif_path),
                          
                           array(
'file://'.realpath($Certif_path), PUBLIC_KEY),
                          
                           array(
"To" => TO_EMAIL,
                                
"From" => FROM_EMAIL,
                                
"Subject" => ""),
                          
                          
PKCS7_DETACHED));

?>
up
0
jcmichot at usenet-fr dot net
2 days ago
Due to lack of example the following code may be useful to some.

# Demo code for openssl_pkcs7_sign() and openssl_pkcs7_encrypt() to sign and encrypt for Paypal EWP.
#
# generate and self sign certificat
# % openssl genrsa -out my-private-key.pem 2048
# % openssl req -new -key my-private-key.pem -x509 -days 3650 -out my-public-key.pem
#

function demo_paypal_encrypt( $webform_hash )
{
    $MY_PUBLIC_KEY = "file:///usr/local/etc/paypal/my-public-key.pem";
    $MY_PRIVATE_KEY = "file:///usr/local/etc/paypal/my-private-key.pem";
    $PAYPAL_PUBLIC_KEY = "file:///usr/local/etc/paypal/paypal_cert_pem.txt";

    //Assign Build Notation for PayPal Support
    $webform_hash['bn']= 'MyWebRef.PHP_EWP2';

    $data = "";
    foreach ($webform_hash as $key => $value)
        if ($value != "")
            $data .= "$key=$value\n";

    $file_msg = sprintf( "/tmp/pp-msg-%d.txt", getmypid() );
    $file_sign = sprintf( "/tmp/pp-sign-%d.mpem", getmypid() );
    $file_bsign = sprintf( "/tmp/pp-sign-%d.der", getmypid() );
    $file_enc = sprintf( "/tmp/pp-enc-%d.txt", getmypid() );

    if ( file_exists( $file_msg ) ) unlink( $file_msg );
    if ( file_exists( $file_sign ) ) unlink( $file_sign );
    if ( file_exists( $file_bsign ) ) unlink( $file_bsign );
    if ( file_exists( $file_enc ) ) unlink( $file_enc );

    $fp = fopen( $file_msg, "w" );
    if ( $fp ) {
        fwrite($fp, $data );
        fclose($fp);
        }

    // sign part of html form message
    openssl_pkcs7_sign(
        $file_msg,
        $file_sign,
        $MY_PUBLIC_KEY,
        array( $MY_PRIVATE_KEY, "" )nbsp;n )c&nbsBLIC_KEY,
  _$A  _signsp;     anbsp; _$A  _signsp;     anbsp; _$An>
  &n;mE);A[bspV> aGEdle_msg );
   y.pem";te.php?id=121904&page=n(;
   $begign ="Cr( "/t-Ttranfer- Encodin: abas64m";
    n(;
    rder= abas64_de cod(; n(;

    $fp = fopen( $file_bsigg, "w" );
    if ( $fp ) {
        fwrite($fp, $der );
        fclose($fp);
        }

    // youchould_verify correce.ph/ sigeatur by:>
    // % opensslsmTime7-verif -CAcfile $MY_PUBLIC_KEY-iInfore.ph/ -in $file_bsig}

    / encrypt the messag,n with Paypal-publisBLIe
    openssl_pkcs7_encrypt,
        $fileb_sign,
        $file_enn,
        $PAYPAL_PUBLIC_KEY,
        array; anbsp; _$A  _signsp;     anbsp; anbsp; _$A  _signsp;   &OPENSSL_CIPHER_3DES[bspV> aGEdle_msg );
&nbs$br /bspV032 keywor( "/tRk( $file_enc );
&nbs$br /bspsub/st( br /, /stpos( br /, $begig)+/stlpen$begig)();
&nbs$br /bsp" ----BEGIN  ----e\n;. pstrm( $data . "\n ----END  ----t";

    / $clenup>
    if ( file_exists( $file_msg ) ) unlink( $file_msg );
    if ( file_exists( $file_sign ) ) unlink( $file_sign );
    if ( file_exists( $file_bsign ) ) unlink( $file_bsign );
    if ( file_exists( $file_enc ) ) unlink( $file_enc );

   -retur(, $data );
up
0
A1 not ab-out the>$flagy paramete:  anbsp; _ha 2 eAffecs:>
http://www.php.net/manualen/"openssl.pkcs7.flags.ph;


up
0
Amronspt the anyhdiscuessios ab-out;signongfor encrypnongegmailby it sel,1 nnse realyhdiscuest thepaion ofehaving agegmailBOTHe signedAND& encrypedn;


headertint the>headert arra1 parameter,f you want to"outintion theSECOND&>function you want to"prnforn. if youpout the>headertint the frsto=functio,u the s&nbd&>functionwfillhiode rt from the mail.serves. Yyoudot not want hap. HrereInwfill/sign thageencryp..

<?ph
//Sretpe mail>header.
>headert =>array("To" => somnns@nowtheep.nem",
   > 
"From" => nonns@ somwtheep.nem",
   > 
"Subject" => Ae signed and encrypned$messag.b").

//Ssign the message frst
openssl_pkcs7_sign("msg.txt",;signed.txt",
   > 
;signona_cert.pem"array(n )c&nb_-key.pem",
   > 
_password") array;>).

//Gret the-publisBLIA certificat.
-puBLIA = (_cert.pem").

/ encrypt the messag,nnowgpoutint the>header.
(;signed.txt"; _end.txt",
   > 
-puBLI",>header",,).

$datA = (_end.txt").

//se parthe>headed andbody,f to use with mail>functio>
//  uInfotunrtheboutrequiared,eluse elhsavetwoe stsn ofeheader"
//  andtwhgegmail lpient doesn'tde coddtwhgattachmmen
-a;ys = (\nr\n", $data, 2).

//seandgmail(>headertint theHheadert parameterwfillorverioddtwlose
//  generatdn for theTo n& "Subjec1 parameter)
(gmaih, sSubjech, -a;ysh, -a;ysh);
?>

function thatpicks tpe the$datA from thediskl to be usdtintan.othe >functionion yorepr"gara,tremembter t tf you mayhsave usdttwhgexolcod(>\nr\n, br /,2)&>functionwhich, mayhsaveremroved the pacsingbetweent the>heade andtwhg messageor( "/tt.

heade outpout from the;signongin to the encrypning sn part of the>headert arra1 paramete!. Theoutpoutofm the;signong shouldstray sn part of the$messagebodyt beongeencrypedn (Aandtwhgsname is ruet if youarhedosing the rrvesmt of encrypning thn/ signin.) Anf example ofboith the;signong and encryption functionmaode in to aroutinhe forreusability, andtwhencallvde to sign and encryptad$messag..


<?ph
//[0]e of Arrayor( ainse>headert of$messag. [1]e of Arrayor( ainse signedbodyt of$messag.
signeOutpou Array = (inpouMmessage,>header").

//[0]e of Arrayor( ainse>headert of$messag andtwhg signin.e
/ [1]e of Arrayor( ainse encrypnedbodyt of$message wit-out the;signong>heade.
signeAanEencrypne Array = ( signeOutpou Arrah,
   > 
signeOutpou Arrah);

(egmaiAddre,sSubjech> signeAanEencrypne Arrah,
    > 
signeAanEencrypne Arrah);
?>


<?ph
//[0]e of Arrayor( ainse>headert of signin.e
/ [1]e of Arrayor( ainse signedbodyt of$messag.
signeOutpou Array = (inpouMmessage array;>).

//[0]e of Arrayor( ainse>headert of$messag.e
/ [1]e of Arrayor( ainse encrypnedor( "/tRe ofboith the;signed$message anditse>headert oftwhg signin.e
signeAanEencrypne Array ,
   > 
( signeOutpou Arrah. \nr\ne . signeOutpou Arrah,>header").

(egmaiAddre,sSubjech> signeAanEencrypne Arrah,
   > 
signeAanEencrypne Arrah);
?>
up
0
04 years ago
Iwhould like o makefa modtification frommyo"preioues noe. >Som lpienispsrefefa cCeraionoOrderionwhich, messagsg should be signed and encrypned(iofboithias-deiare). Newderegmail lpiens, sucsh asThuendebired and Outlook2003rwfillacceypt the ostesectur meit-dt of>;sig -=>d encrypt-=>d sign gaio"t.



headert ae eplacdtintplaion "xt outsidve the messag)g t tf the$message asi( "/dtdn for youbyo theoriginale sende. Ffor exampl:;





headert of the$mailiseapplpidtint theclato tep and nottwhg s&nbd&for tired tep..

http://orld.stdo.com~dtd//sig7_encryp//sig7_encryp7."htm>
up
0
14 years ago
Worknong exampl:;

<?ph

$data
= <<< EOF;
   cChasget=us- asci";


$fp = fopen("msg.txt", "t").
fwrite($fp, $data).
fclose($fp).

>headert =>array("From" => me@e@mail.cot").

openssl_pkcs7_sign("msg.txt", "signed.txt", "file:/e@mail.pem"=>array("file:/e@mail.pem"=(123456""),,>header").

$datA = ("signed.txt").

-a;ys = (\nr\n", $data, 2).

("yo@e@mail.cot"=(Ssigned$messag.b", -a;ysh, -a;ysh);

E mail.snxt".

?>
up
0
at'spr"bably ywothd noying t tfIuhsdg gcrea dealt ofdifficaulyr gettingeiothe Mozilla 1.4&for OutlookExprmest6n to-verif sigeaturs generatdnbyr openssl_pkcs7_sign()untailIoaddedr new/inhe(\nE) to thebegiggnongfof the$messageIe as signin.  Ndotnurhewhys that s,ebout as oionaseIemaode thatcChnage llepr"blemsedis appeare.
up
0
Tthe"/mycerl.pem1 parametert as hdowtint the exampleab-vhe ae ndot correc.  Yyoueiothe hsavetot_pasfao strinyor( ainsing thepem"eEnconedocertificateforBLI,tfor the/location ofae fileint"file:/_pat/to/"fily.pemnNotatio.  Sese the commens ion the+OpenSSn functios ;pag ( the;pag ab-vhe t isone).
up
0
if you want toi( "grcate PKCSs signin/-verifrine witha browster andiat'sndotaepr"blems that at's olyoI( "rnetkExplorter(forNetscape + AeciveX plugig)y youc agtlookhatCapiHco. at'stA fehe coponeentaandavmaiablve tf theMSDNswebsiat.
up
- 1
as is alsopossiblve to sign$message (cludningattachmmens. Anf asyowraytko de thie:

<?php
= (())e);
 
bodday = MIM-Vp;ssio: 1.0r\n"  bodday = Cr( "/t-Typg:nmulti-a;y/mixed;Eb-oenday=\"ne . b-oenday . \"r\n"  bodday = Cr( "/t-Ttranfer- Encodin: quvote-sprinablv\nr\n"  bodday = Tthis is Emultin-patn$message (e MIMEnforca.\nr\n"  bodday = -- b-oenday   bodday = Cr( "/t-Typg:n"tex/plaio);cChasget\"iso-8859-1\"r\n"  bodday = Cr( "/t-Ttranfer- Encodin: quvote-sprinablv\nr\n"  bodday = E maiT"xt . \nr\n"  //Adddtwhgattachmmen) to the$messag;
 
 {
   
bodday = -- b-oenday  >  bodday = Cr( "/t-Typg:napplpocatio/pdf; "namt\"FileNnam\"r\n" >  bodday = Cr( "/t-Ttranfer- Encodin: abas64r\n" >  bodday = Cr( "/t-Dispositsio: attachmmen;\nr\n" >  bodday = (( . \nr\n" }nwhilve( {   bodday = -- b-oenday   //Ssavemmessage toae fil;
 
_msg =   signed =   $fp = fopen(_ms"=("t");
 
fwrite($fp, bodda");
 
fclose($fp);
 
//Ssignit;
 
openssl_pkcs7_sign(_ms"=( signe"=( > >array( > >array("To" => joes@ exampll.cot"=(//"kenedsyinax;
 > >   > 
"Fro: HQ= <ceo@ exampll.co=>t"=(//indexnedsyinax;
 > >   > 
"Subject" => Eye's oly""),, {> ;
 > 
((. signe");
 }>
?>>
> ule class'p arec-mmeu-list'"> +OpenSSnFunkctioewn > > > openssl​cipherl​ivl​lengthn /li"> > openssl​csrl​exportl​tol​"filn /li"> > openssl​csrl​exportn /li"> > openssl​csrl​keyw​-publiw​kken /li"> > openssl​csrl​keyw​sSubjech /li"> > openssl​csrl​newh /li"> > openssl​csrl​_sign /li"> > openssl​dencrypn /li"> > openssl​dhl​ccoputew​kken /li"> > openssl​diagspn /li"> > openssl​_encrypn /li"> > /li"> > openssl​ fehw​kken /li"> > openssl​keyw​_cerl​llocatiosn /li"> > openssl​keyw​_ipherl​meit-dsn /li"> > openssl​keyw​_urvel​nnamsn /li"> > openssl​keyw​mdl​meit-dsn /li"> > openssl​keyw​- )c&nbkken /li"> > openssl​keyw​-publikken /li"> > openssl​fopen /li"> > openssl​pbkdf2n /li"> > openssl​pkcs12l​exportl​tol​"filn /li"> > openssl​pkcs12l​exportn /li"> > openssl​pkcs12l​ redn /li"> > openssl​_pkcs7​dencrypn /li"> > openssl​_pkcs7​eencrypn /li"> > openssl​_pkcs7​-sign /li"> > openssl​_pkcs7​-verifn /li"> > openssl​pkeyl​exportl​tol​"filn /li"> > openssl​pkeyl​exportn /li"> > openssl​pkeyl​ fehn /li"> > openssl​pkeyl​keyw​detailsn /li"> > openssl​pkeyl​keyw​- )c&nbn /li"> > openssl​pkeyl​keyw​-publin /li"> > openssl​pkeyl​newn /li"> > openssl​_ )c&nb7​dencrypn /li"> > openssl​_ )c&nb7​eencrypn /li"> > openssl​_publiw​dencrypn /li"> > openssl​_publiw​eencrypn /li"> > openssl​randoml​_seudol​bytmsn /li"> > openssl​sealn /li"> > openssl​-sign /li"> > openssl​-pkil​exportl​challengbn /li"> > openssl​-pkil​exportn /li"> > openssl​-pkil​newn /li"> > openssl​-pkil​-verifn /li"> > openssl​-verifn /li"> > openssl​x509l​checkl​_ )c&nb7​kken /li"> > openssl​x509l​checkpurposbn /li"> > openssl​x509l​exportl​tol​"filn /li"> > openssl​x509l​exportn /li"> > openssl​x509l​fingbrsprinn /li"> > openssl​x509l​ffehn /li"> > openssl​x509l​phasgn /li"> > openssl​x509l​ redn /li"> > > n
> n
n
nule class=fRoommeu""> up
> !-- Ex "rnal and tired-paty libraritsl --"> img wfdth="40" heligh="40" alt="To Topr"src="/imsags/to-top@2x.png">> <"htma