本文整理汇总了PHP中openssl_pkey_new函数的典型用法代码示例。如果您正苦于以下问题:PHP openssl_pkey_new函数的具体用法?PHP openssl_pkey_new怎么用?PHP openssl_pkey_new使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了openssl_pkey_new函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testOpenSSLSignature
public function testOpenSSLSignature()
{
if (!extension_loaded('OpenSSL')) {
$this->markTestSkipped("Need OpenSSL extension");
}
// Generate a private key on the fly.
$passphrase = uniqid();
$passfile = PHING_TEST_BASE . '/etc/tasks/ext/pharpackage/pass.txt';
file_put_contents($passfile, $passphrase);
$pkey = openssl_pkey_new();
openssl_pkey_export_to_file($pkey, PHING_TEST_BASE . '/etc/tasks/ext/pharpackage/priv.key', $passphrase);
$this->executeTarget(__FUNCTION__);
// Make sure we are dealing with an OpenSSL signature.
// (Phar silently falls back to an SHA1 signature
// whenever it fails to add an OpenSSL signature)
$dest = PHING_TEST_BASE . '/etc/tasks/ext/pharpackage/pharpackage.phar';
$this->assertFileExists($dest);
$phar = new Phar($dest);
$signature = $phar->getSignature();
$this->assertEquals('OpenSSL', $signature['hash_type']);
unlink(PHING_TEST_BASE . '/etc/tasks/ext/pharpackage/priv.key');
unlink(PHING_TEST_BASE . '/etc/tasks/ext/pharpackage/pharpackage.phar.pubkey');
unlink(PHING_TEST_BASE . '/etc/tasks/ext/pharpackage/pass.txt');
unlink($dest);
}
示例2: generateSslKeypair
function generateSslKeypair($commonName, $keyLength)
{
$key = openssl_pkey_new(array("private_key_bits" => $keyLength));
$default = getDefaultConfPath();
if (file_exists($default . "/cert-overrides.ini")) {
$confFile = $default . "/cert-overrides.ini";
} else {
$confFile = $_SERVER["DOCUMENT_ROOT"] . "/conf/cert.ini";
}
$certConf = parse_ini_file($confFile, true);
$dn = $certConf["dn"];
$dn["commonName"] = $commonName;
$cert = openssl_csr_new($dn, $key);
// Creating a new X509 Certificate Signing Request
if ($e = error_get_last()) {
// Issues found in parsing the arguments will get a warning. A CSR is created, nonetheless
throw new Exception("Error occured:" . $e["message"]);
}
$signed = openssl_csr_sign($cert, null, $key, $certConf["csr"]["validity_in_days"], array("config" => $confFile, "config_section_name" => "csr", "x509_extensions" => "clientx509_ext"));
// Self-signed X509 certificate with SHA256 digest and extensions specified in local openssl.conf
if (!$signed) {
throw new Exception("Error occured while signing certificate");
}
openssl_pkey_export($key, $privateKey);
// Export private-key to $privateKey
openssl_x509_export($signed, $clientCert);
// Export signed-certificate to $clientCert without Extra Details
return array($clientCert, $privateKey);
}
示例3: get_keys
static public function get_keys($login,$full_name) {
$CA_CERT = base_url()."data/key/CA_DOC.csr";
$CA_KEY = base_url()."data/key/CA_DOC_priv.key";
$config = array(
"private_key_type"=>OPENSSL_KEYTYPE_RSA,
"private_key_bits"=>512
);
$res = openssl_pkey_new($config);
$privKey = '';
openssl_pkey_export($res,$privKey);
$arr = array(
"organizationName" => "Фізична особа",
"organizationalUnitName" => "Фізична особа",
"commonName" => $full_name,
"UID" => $login,
"countryName" => "UA"
);
$csr = openssl_csr_new($arr,$privKey);
$cert = openssl_csr_sign($csr,file_get_contents($CA_CERT),file_get_contents($CA_KEY),730);
openssl_x509_export($cert,$str_cert);
$public_key = openssl_pkey_get_public($str_cert);
$public_key_details = openssl_pkey_get_details($public_key);
$public_key_string = $public_key_details['key'];
return array('private'=>$privKey,'cert'=>$str_cert,'public'=>$public_key_string);
}
示例4: generate
/**
* Generates a new key pair with the given length in bits.
*
* @api
* @param int $bits length of the key
* @return KeyPair generated key pair
*/
public function generate($bits = 2048)
{
if (!is_int($bits)) {
throw new \InvalidArgumentException(sprintf("\$bits must be of type int, %s given", gettype($bits)));
}
if ($bits < 2048) {
throw new \InvalidArgumentException("Keys with fewer than 2048 bits are not allowed!");
}
$configFile = $defaultConfigFile = __DIR__ . "/../res/openssl.cnf";
if (class_exists("Phar") && !empty(Phar::running(true))) {
$configContent = file_get_contents($configFile);
$configFile = tempnam(sys_get_temp_dir(), "acme_openssl_");
file_put_contents($configFile, $configContent);
register_shutdown_function(function () use($configFile) {
@unlink($configFile);
});
}
$res = openssl_pkey_new(["private_key_type" => OPENSSL_KEYTYPE_RSA, "private_key_bits" => $bits, "config" => $configFile]);
$success = openssl_pkey_export($res, $privateKey, null, ["config" => $configFile]);
if ($configFile !== $defaultConfigFile) {
@unlink($configFile);
}
if (!$success) {
openssl_pkey_free($res);
throw new \RuntimeException("Key export failed!");
}
$publicKey = openssl_pkey_get_details($res)["key"];
openssl_pkey_free($res);
// clear error buffer, because of minimalistic openssl.cnf
while (openssl_error_string() !== false) {
}
return new KeyPair($privateKey, $publicKey);
}
示例5: genCSR
private function genCSR()
{
$pkey = openssl_pkey_new(array('private_key_bits' => 2048));
$res = openssl_csr_new(array(), $pkey);
openssl_csr_export($res, $out);
return $out;
}
示例6: makeKeys
public function makeKeys($distinguishedName, $passphrase = NULL, $certCA = NULL, $keyCA)
{
// keep track of the distinguished name
$this->dn = $distinguishedName;
// generate the pem-encoded private key
$config = array('digest_alg' => 'sha1', 'private_key_bits' => 1024, 'encrypt_key' => TRUE);
$key = openssl_pkey_new($config);
// generate the certificate signing request...
$csr = openssl_csr_new($this->dn, $key, $config);
// and use it to make a self-signed certificate
$this->serialNumber = rand();
$cert = openssl_csr_sign($csr, NULL, $key, 365, $config, time());
// make openssl forget the key
openssl_free_key($keyCA);
// export private and public keys
openssl_pkey_export($key, $this->privatekey, $passphrase, $config);
//openssl_pkey_export_to_file ( $this->privatekey , "server.key", $passphrase, $config )
openssl_x509_export($cert, $this->certificate);
// parse certificate
$this->x509 = openssl_x509_parse($cert);
if (isset($this->serialNumber)) {
$outfilename = '/var/www/html/' . $this->serialNumber;
// Gets an exportable representation of a key into a file
openssl_pkey_export_to_file($key, $outfilename . '.pem', $passphrase, $config);
}
openssl_x509_export_to_file($this->certificate, $outfilename . '.crt', TRUE);
return TRUE;
// end of makeKeys() method
}
示例7: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$init = $this->getHelper('init')->getInit();
$basedir = $init->getBaseDir();
$fprikey = $basedir . '/app/config/key/';
$fpubkey = $basedir . '/app/config/key/';
$namePri = "private.pkey";
$namePub = "public.pkey";
if (!file_exists($fprikey . $namePri) || !file_exists($fpubkey . $namePub)) {
if (!file_exists($fprikey)) {
mkdir($fprikey, 0777, true);
}
if (!file_exists($fpubkey)) {
mkdir($fpubkey, 0777, true);
}
$key = openssl_pkey_new();
openssl_pkey_export($key, $privatekey);
$publickey = openssl_pkey_get_details($key);
$publickey = $publickey["key"];
file_put_contents($fprikey . $namePri, $privatekey);
file_put_contents($fpubkey . $namePub, $publickey);
$output->writeln("Chaves geradas com sucesso!");
} else {
$output->writeln("Chaves já existem!");
}
}
示例8: run
public function run()
{
if (strrev($this->input['folder']) !== DIRECTORY_SEPARATOR) {
$this->input['folder'] .= DIRECTORY_SEPARATOR;
}
$files = [];
foreach (['pub', 'key', 'crt', 'csr'] as $extension) {
$files[$extension] = sprintf('%s%s%s.%s', $this->input['folder'], $this->input['prefix'], $this->input['hostname'], $extension);
}
foreach ($files as $file) {
if (file_exists($file)) {
throw new RuntimeException(sprintf('File exist: %s', $file));
}
}
$dn = array("countryName" => $this->input['country'], "stateOrProvinceName" => $this->input['state-or-province-name'], "localityName" => $this->input['locality-name'], "organizationName" => $this->input['organization-name'], "organizationalUnitName" => $this->input['organizational-unit-name'], "commonName" => $this->input['common-name'], "emailAddress" => $this->input['email-address']);
// Create the private and public key
$res = openssl_pkey_new(['digest_alg' => $this->input['alg'], 'private_key_bits' => $this->input['bits'], 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
// Generate a certificate signing request
$csr = openssl_csr_new(array_filter($dn), $res);
// Creates a self-signed cert
$sscert = openssl_csr_sign($csr, null, $res, $this->input['days']);
openssl_csr_export($csr, $out);
file_put_contents($files['csr'], $out);
// Export certfile
openssl_x509_export($sscert, $out);
file_put_contents($files['crt'], $out);
// Extract the private key from $res to $privKey
openssl_pkey_export($res, $out);
file_put_contents($files['key'], $out);
// Extract the public key from $res to $pubKey
$out = openssl_pkey_get_details($res);
file_put_contents($files['pub'], $out["key"]);
}
示例9: createToken
public function createToken($sKey)
{
if (!Phpfox::getParam('apps.enable_api_support')) {
$this->error('api.enable_api_support', 'API support for this community is currently disabled.');
return $this->_sendResponse();
}
if (empty($sKey)) {
$this->error('api.unable_to_find_api_key', 'Unable to find API key.');
return $this->_sendResponse();
}
$aApp = $this->database()->select('a.*, ai.user_id AS installed_user_id')->from(Phpfox::getT('app_key'), 'ak')->join($this->_sTable, 'a', 'a.app_id = ak.app_id')->join(Phpfox::getT('app_installed'), 'ai', 'ai.app_id = a.app_id AND ai.user_id = ak.user_id')->where('ak.key_check = \'' . $this->database()->escape($sKey) . '\'')->execute('getSlaveRow');
if (!isset($aApp['app_id'])) {
$this->error('api.unable_to_find_api_key', 'Unable to find API key.');
return $this->_sendResponse();
}
$res = openssl_pkey_new($this->_aOpenSSLConfig);
openssl_pkey_export($res, $privKey, $aApp['private_key'], $this->_aOpenSSLConfig);
$pubKey = openssl_pkey_get_details($res);
if ($sPlugin = Phpfox_Plugin::get('api.service_api_createtoken_1')) {
eval($sPlugin);
}
$this->database()->delete(Phpfox::getT('app_access'), 'app_id = ' . $aApp['app_id'] . ' AND user_id = ' . $aApp['installed_user_id']);
$this->database()->insert(Phpfox::getT('app_access'), array('app_id' => $aApp['app_id'], 'user_id' => $aApp['installed_user_id'], 'token' => md5($pubKey['key']), 'token_key' => $pubKey['key'], 'token_private' => $privKey, 'time_stamp' => PHPFOX_TIME));
return json_encode(array('token' => base64_encode($pubKey['key'])));
}
示例10: generate
/**
* Create a random private key of the given length (in bits).
*
* You can use predefined constants to have valid keylength values.
*
* The higher the key length, the higher the security the higher the required time to generate the key.
*
* Usage example:
*
* <code>
* //give a name to the file containing the generation result
* $filename = APPLICATION_DIR."newkey.private.pem";
*
* //generate the new key
* $serailized_key = PrivateKey::generate(PrivateKey::RSA4096);
*
* //export to file the serialized key
* file_put_contents($filename, $serailized_key);
* //NOTE: this example is really BAD because the file is NOT encrypted
*
* //yes, you can load private keys directly from file
* $private_key = new PrivateKey("file://".$filename);
* </code>
*
* @param int $keyLength the length (in bits) of the private key to e generated
*
* @return string the serialized private key
*
* @throws \InvalidArgumentException the given key length is not an integer power of two
* @throws AsymmetricException the error occurred while generating and exporting the new private key
*/
public static function generate($keyLength = self::RSA4096)
{
if (!is_integer($keyLength)) {
throw new \InvalidArgumentException('The key length must be given as an integer number which is a power of two');
} elseif (($keyLength & $keyLength - 1) != 0 || $keyLength == 0) {
throw new \InvalidArgumentException('The key length must be a power of two');
}
//if the key length is extremely long, a very long time will be needed to generate the key, and it is necessary ti set no time limits to generate it
if ($keyLength == self::RSAEXTREME) {
set_time_limit(0);
}
//build the configuration array
$config = ['digest_alg' => 'sha512', 'private_key_bits' => $keyLength, 'private_key_type' => OPENSSL_KEYTYPE_RSA];
//use the application openssl configuration
if (!is_null(Environment::GetCurrentEnvironment())) {
$config = array_merge($config, ['config' => file_exists(Environment::GetCurrentEnvironment()->GetConfigurationProperty('APPLICATION_DIR') . 'openssl.cnf') ? Environment::GetCurrentEnvironment()->GetConfigurationProperty('APPLICATION_DIR') . 'openssl.cnf' : null]);
}
//create a new private key
$privateKey = openssl_pkey_new($config);
//check the result
if (!is_resource($privateKey)) {
throw new AsymmetricException('The key generation is not possible due to an unknown ' . openssl_error_string(), 8);
}
//extract the private key string-encoded from the generated private key
$pKeyEncoded = '';
openssl_pkey_export($privateKey, $pKeyEncoded, null, $config);
//free the memory space used to hold the newly generated key
openssl_free_key($privateKey);
//check for the result
if (!is_string($pKeyEncoded)) {
throw new AsymmetricException("The key generation was completed, but the result couldn't be exported", 9);
}
//return the operation result
return $pKeyEncoded;
}
示例11: generateKeys
/**
* Generate public and private key
* @param array $options
*/
public function generateKeys(array $options = self::DEFAULT_PUBLIC_KEY_OPTIONS)
{
$keys = openssl_pkey_new($options);
$this->publicKey = openssl_pkey_get_details($keys)["key"];
openssl_pkey_export($keys, $this->privateKey);
openssl_pkey_free($keys);
}
示例12: t2
function t2()
{
$config = array("digest_alg" => "sha256", "private_key_bits" => 2048, "encrypt_key" => 1, "encrypt_key_cipher" => OPENSSL_CIPHER_AES_256_CBC);
// Create the keypair
$res = openssl_pkey_new($config);
var_dump($res);
// Get private key
openssl_pkey_export($res, $privkey, 'libo', $config);
// Get public key
$publickey = openssl_pkey_get_details($res);
$publickey = $publickey["key"];
echo "Private Key:\n{$privkey}\n\nPublic Key:\n{$publickey}\n\n";
$cleartext = '1234 5678 9012 3456';
echo "Clear text:\n{$cleartext}\n\n";
openssl_public_encrypt($cleartext, $crypttext, $publickey);
echo "Crypt text:\n" . base64_encode($crypttext) . "\n";
$priv = openssl_pkey_get_private($privkey, "libo");
var_dump($priv);
if (!$priv) {
echo "\nGet private key fail!\n";
exit(1);
}
openssl_private_decrypt($crypttext, $decrypted, $priv);
echo "\nDecrypted text:\n{$decrypted}\n\n";
}
示例13: createNewcertificate
function createNewcertificate()
{
global $gbl, $login, $ghtml;
$cerpath = "server.crt";
$keypath = "server.key";
$requestpath = "a.csr";
$ltemp["countryName"] = "IN";
$ltemp["stateOrProvinceName"] = "Bn";
$ltemp["localityName"] = "Bn";
$ltemp["organizationName"] = "LxCenter";
$ltemp["organizationalUnitName"] = "Kloxo";
$ltemp["commonName"] = "Kloxo";
$ltemp["emailAddress"] = "contact@lxcenter.org";
$privkey = openssl_pkey_new();
openssl_pkey_export_to_file($privkey, $keypath);
$csr = openssl_csr_new($ltemp, $privkey);
openssl_csr_export_to_file($csr, $requestpath);
$sscert = openssl_csr_sign($csr, null, $privkey, 365);
openssl_x509_export_to_file($sscert, $cerpath);
$src = getcwd();
$dest = '/usr/local/lxlabs/kloxo/ext/lxhttpd/conf';
root_execsys("lxfilesys_mkdir", $dest . "/ssl.crt/");
root_execsys("lxfilesys_mkdir", $dest . "/ssl.key/");
root_execsys("lxfilesys_mv", "{$src}/{$cerpath}", $dest . "/ssl.crt/" . $cerpath);
root_execsys("lxfilesys_mv", "{$src}/{$keypath}", $dest . "/ssl.key/" . $cerpath);
root_execsys("lxfilesys_mv", "{$src}/{$requestpath}", "{$dest}/{$requestpath}");
}
示例14: generateSslKeypair
function generateSslKeypair($commonName, $mail, $keyLength)
{
$key = openssl_pkey_new(array("private_key_bits" => $keyLength));
$certConf = parse_ini_file("cert.conf", true);
$dn = $certConf["dn"];
$dn["commonName"] = $commonName;
$dn["emailAddress"] = $mail;
$cert = openssl_csr_new($dn, $key);
// Creating a new X509 Certificate Signing Request
if ($e = error_get_last()) {
// Issues found in parsing the arguments will get a warning. A CSR is created, nonetheless
throw new Exception("Error occured:" . $e["message"]);
}
$signed = openssl_csr_sign($cert, null, $key, $certConf["csr"]["validity_in_days"], array("config" => "../core/cert.conf", "config_section_name" => "csr", "x509_extensions" => "clientx509_ext"));
// Self-signed X509 certificate with SHA256 digest and extensions specified in local openssl.conf
if (!$signed) {
throw new Exception("Error occured while signing certificate");
}
openssl_pkey_export($key, $privateKey);
// Export private-key to $privateKey
openssl_x509_export($signed, $clientCert, FALSE);
// Export signed-certificate to $clientCert
openssl_x509_export($signed, $publicKey);
// Export public-key from the signed-certificate to $publicKey
return array($clientCert, $publicKey, $privateKey);
}
示例15: testCreate
public function testCreate()
{
$container = ContainerLoader::buildTestContainer();
$em = $container->get('doctrine.orm.entity_manager');
$client = new Client();
$client->setClientId($token = 'test-client-' . rand());
$client->setClientSecret('very-secure');
$client->setRedirectUri(array('http://brentertainment.com'));
$em->persist($client);
$em->flush();
$public_key = new ClientPublicKey();
$public_key->setClient($client);
// create and set the public key
$res = openssl_pkey_new();
// Extract the public key from $res to $pubKey
$pubKeyDetails = openssl_pkey_get_details($res);
$pubKey = $pubKeyDetails['key'];
$public_key->setPublicKey($pubKey);
$em->persist($public_key);
$em->flush();
// test direct access
$stored = $em->find('OAuth2\\ServerBundle\\Entity\\ClientPublicKey', array('client_id' => $client->getClientId()));
$this->assertNotNull($stored);
$this->assertEquals($pubKey, $stored->getPublicKey());
}