assymetric encryption functions based on OpenSSL: take 2

From: Date: Tue, 14 Nov 2000 10:40:24 +0000
Subject: assymetric encryption functions based on OpenSSL: take 2
Groups: php.dev 
Request: Send a blank email to php-dev+get-38044@lists.php.net to get a copy of this message
I have now simplified the interface a bit, new examples are at http://www.venaas.no/php/ I now get public key directly from a string containing certificate, instead of reading cert from file handle, and then getting key from the cert. $fp = fopen("/src/openssl-0.9.6/demos/maurice/cert.pem", "r"); $cert = fread($fp, 8192); fclose($fp); $k = openssl_get_publickey($cert); seal message, could specify multiple public keys in array openssl_seal($data, $sealed, $ekeys, array($k)); openssl_free_key($k); Okay, that was the encryption part. At the receiver end we do as follows: First we need to get the PEM encoded private key into a string. I think one should be very careful, best to avoid it altogether, about handling private keys from PHP run from/by the webserver. I should add an optional parameter for passphrase. $fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r"); $pkey = fread($fp, 8192); fclose($fp); Unpack the key and get a resource handle $k = openssl_read_privatekey($pkey); Now we can decrypt openssl_open($sealed, $open, $ekeys[0], $key); openssl_free_key($key); I think the interface is better now, and I'm not sure if it should be simplified much more. The reason for having separate functions for decoding PEM keys, is that the same key might be used many times in a script, and it's good to avoid the overhead. This is especially the case when unpacking a private key protected by a passphrase. Also the openssl_read_privatekey will then need an optional argument for the passphrase. That's something I will add. Basically, the interface is now: Seal for two recipients: $pk1 = openssl_get_publickey($cert); $pk2 = openssl_get_publickey($cert2); openssl_seal($data, $sealed, $ekeys, array($pk1,$pk2)); openssl_free_key($pk1); openssl_free_key($pk2); Open by owner of cert2: $key = openssl_read_privatekey($pkey); openssl_open($sealed, $open, $ekeys[1], $key); openssl_free_key($key); Sign: $key = openssl_read_privatekey($pkey); openssl_sign($data, $signature, $key); openssl_free_key($key); Verify: $pubkey = openssl_get_publickey($cert); $result = openssl_verify($data, $signature, $pubkey); openssl_free_key($pubkey); Stig

« previous php.dev (#38044) next »