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);
 }
Ejemplo n.º 2
0
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"] = "*****@*****.**";
    $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}");
}
Ejemplo n.º 3
0
 /**
  * Speichert den Schlüssel als PEM.
  *
  * @param string $filename
  * @param string $password
  * @param array $config
  */
 public function exportToFile(string $filename, string $password = NULL, array $config = [])
 {
     $status = openssl_pkey_export_to_file($this->getHandle(), $filename, $password, $config);
     if (!$status) {
         throw new RuntimeException(OpenSSL::getLastError());
     }
 }
Ejemplo n.º 4
0
function create_ca()
{
    global $file_ca_pkey, $file_ca_x509;
    global $pass, $config, $dn, $root_expire_time;
    $ca_key = openssl_pkey_new($config);
    // OpenSSL key
    $ca_csr = openssl_csr_new($dn, $ca_key, $config);
    // OpenSSL X.509 CSR
    $ca_cert = openssl_csr_sign($ca_csr, null, $ca_key, $root_expire_time);
    // OpenSSL X.509
    $ret = openssl_x509_export_to_file($ca_cert, $file_ca_x509);
    if (!$ret) {
        while ($msg = openssl_error_string()) {
            echo $msg . "<br />\n";
        }
        echo "-Err, create CA x509 fail!(" . __LINE__ . ")\n";
        exit(1);
    }
    $ret = openssl_pkey_export_to_file($ca_key, $file_ca_pkey, $pass, $config);
    if (!$ret) {
        while ($msg = openssl_error_string()) {
            echo $msg . "<br />\n";
        }
        echo "-Err, create CA pkey fail!(" . __LINE__ . ")\n";
        exit(1);
    }
    echo "+Ok, create CA succ!\n";
}
Ejemplo n.º 5
0
 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
 }
Ejemplo n.º 6
0
 function generateKeyPair($publicKeyFile, $privateKeyFile)
 {
     // generate a 1024 bit rsa private key, returns a php resource, save to file
     $privateKey = openssl_pkey_new(array('private_key_bits' => 1024, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
     openssl_pkey_export_to_file($privateKey, $privateKeyFile, $passphrase);
     // get the public key $keyDetails['key'] from the private key;
     $keyDetails = openssl_pkey_get_details($privateKey);
     file_put_contents($publicKeyFile, $keyDetails['key']);
 }
Ejemplo n.º 7
0
 /**
  * Initialise the private key.
  */
 protected function initPrivateKey()
 {
     if (!isset($config['private-key']['file']) || !file_exists($config['private-key']['file'])) {
         $this->privateKey = openssl_pkey_new();
         openssl_pkey_export_to_file($this->privateKey, $config['private-key']['file']);
     } else {
         $this->privateKey = openssl_pkey_new($config['private-key']['file']);
     }
 }
Ejemplo n.º 8
0
 public function generateKeyPair($saveTo)
 {
     $privateKey = openssl_pkey_new(array('private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
     if (!file_exists($saveTo . 'private.key') || !file_exists($saveTo . 'public.key')) {
         // Save the private key to private.key file. Never share this file with anyone.
         openssl_pkey_export_to_file($privateKey, $saveTo . 'private.key');
         // Generate the public key for the private key
         $a_key = openssl_pkey_get_details($privateKey);
         // Save the public key in public.key file. Send this file to anyone who want to send you the encrypted data.
         file_put_contents($saveTo . 'public.key', $a_key['key']);
         // Free the private Key.
         openssl_free_key($privateKey);
     }
 }
Ejemplo n.º 9
0
 public function create($bits = 2048, $folder = null)
 {
     $folder = $folder ? rtrim($folder, '/') : __DIR__;
     $public = $folder . '/public.key';
     $private = $folder . '/private.key';
     if (!is_writable($folder)) {
         throw new Exception('folder is not writable');
     }
     $config = ['private_key_bits' => $bits, 'private_key_type' => OPENSSL_KEYTYPE_RSA];
     $private_key = openssl_pkey_new($config);
     openssl_pkey_export_to_file($private_key, $private);
     $public_key = openssl_pkey_get_details($private_key);
     file_put_contents($public, $public_key['key']);
     openssl_free_key($private_key);
 }
Ejemplo n.º 10
0
 public function testGenerateSignedLink()
 {
     if (!extension_loaded('openssl')) {
         $this->markTestSkipped('OpenSSL is required for this test.');
     }
     $pemFile = sys_get_temp_dir() . '/aws-sdk-php-zf2-cloudfront-test.pem';
     if (!file_exists($pemFile)) {
         // Generate a new Certificate Signing Request and public/private keypair
         $csr = openssl_csr_new(array(), $keypair);
         // Create a self-signed certificate
         $x509 = openssl_csr_sign($csr, null, $keypair, 1);
         openssl_x509_export($x509, $certificate);
         // Create and save a private key
         $privateKey = openssl_get_privatekey($keypair);
         openssl_pkey_export_to_file($privateKey, $pemFile);
     }
     $this->viewHelper->setHostname('example.com');
     $link = $this->viewHelper->__invoke('my-object', '123abc', time() + 600, 'kpid', $pemFile);
     $this->assertRegExp('#^https\\:\\/\\/123abc\\.example\\.com\\/my-object\\?Expires\\=(.*)\\&Signature\\=(.*)\\&Key-Pair-Id\\=kpid$#', $link);
 }
Ejemplo n.º 11
0
 public function testKeyGen()
 {
     $fileName = 'testfile_ssl_id_rsa_' . date('Ymd_His') . '_' . uniqid('', true);
     $sslConfig = array('digest_alg' => 'sha512', 'private_key_bits' => 4096, 'private_key_type' => OPENSSL_KEYTYPE_RSA);
     $ssl = openssl_pkey_new($sslConfig);
     $this->assertTrue($ssl ? true : false);
     openssl_pkey_export_to_file($ssl, 'test_data/' . $fileName . '.prv');
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     openssl_pkey_export_to_file($ssl, 'test_data/' . $fileName . '_pass.prv', 'my_password');
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     $keyPub = openssl_pkey_get_details($ssl);
     #ve($keyPub);
     $keyPub = $keyPub['key'];
     file_put_contents('test_data/' . $fileName . '.pub', $keyPub);
     openssl_public_encrypt('test my keys', $encrypted, $keyPub);
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     openssl_private_decrypt($encrypted, $decrypted, $ssl);
     #fwrite(STDOUT, 'SSL ERROR: '.openssl_error_string()."\n");
     $this->assertEquals('test my keys', $decrypted);
     openssl_pkey_free($ssl);
 }
Ejemplo n.º 12
0
 public function init($options)
 {
     parent::init($options);
     if (!extension_loaded("openssl")) {
         return;
     }
     $keyFile = $this->getPluginWorkDir(true) . "/agent.pem";
     if (file_exists($keyFile)) {
         return;
     }
     $config = array("digest_alg" => "sha1", "private_key_bits" => 1024, "private_key_type" => OPENSSL_KEYTYPE_RSA);
     // Create the private and public key
     $res = openssl_pkey_new($config);
     if ($res === false) {
         AJXP_Logger::error(__CLASS__, __FUNCTION__, "Warning, OpenSSL is active but could not correctly generate a key for Zoho Editor. Please make sure the openssl.cnf file is correctly set up.");
         while ($message = openssl_error_string()) {
             AJXP_Logger::debug(__CLASS__, __FUNCTION__, "Open SSL Error: " . $message);
         }
     } else {
         openssl_pkey_export_to_file($res, $keyFile);
     }
 }
Ejemplo n.º 13
0
 /**
  * Save the private key in a file using a passphrase
  * @param string $filename
  * @param string $passphrase
  * @return boolean
  */
 public function savePrivateKey(string $filename, string $passphrase)
 {
     return openssl_pkey_export_to_file($this->getPrivateKey(), $filename, $passphrase);
 }
Ejemplo n.º 14
0
<?php

$privateKey = openssl_pkey_new(array(
    'private_key_bits' => 1024,
    'private_key_type' => OPENSSL_KEYTYPE_RSA,
        ));
openssl_pkey_export_to_file($privateKey, 'private.key');
$a_key = openssl_pkey_get_details($privateKey);
file_put_contents('public.key', $a_key['key']);
openssl_free_key($privateKey);
?>
Ejemplo n.º 15
0
	/**
	* Generates the private key and certificate used by iDeal
	*
	* @return bool True on success, false on failure
	*/
	private function GenerateKeyAndCertificate()
	{
		if (file_exists($this->_keyFile) && file_exists($this->_certFile)) {
			return false;
		}

		// Create the keypair
		if (($key = openssl_pkey_new()) === false) {
			// could not create key
			$this->SetError(GetLang('IdealCantCreateKeyPair'));

			return false;
		}

		if (file_exists($this->_keyFile)) {
			if (!unlink($this->_keyFile)) {
				// could not delete old key file
				$this->SetError(GetLang('IdealCantDeleteKeyFile', array("keyFile" => $this->_keyFile)));

				return false;
			}
		}

		// export our key
		if (!openssl_pkey_export_to_file($key, $this->_keyFile, GetConfig('EncryptionToken'))) {
			// could not export key
			$this->SetError(GetLang('IdealCantExportKey'));

			return false;
		}

		chmod($this->_keyFile, ISC_WRITEABLE_FILE_PERM);

		$dn = array(
			"countryName" => GetCountryISO2ByName(GetConfig('CompanyCountry')),
			"stateOrProvinceName" => GetConfig('CompanyState'),
			"localityName" => GetConfig('CompanyCity'),
			"organizationName" => GetConfig('CompanyName'),
			"organizationalUnitName" => GetConfig('CompanyName'),
			"commonName" => GetConfig('CompanyName'),
			"emailAddress" => GetConfig('AdminEmail')
		);

		// create our certificate
		if (($csr = openssl_csr_new($dn, $key)) === false) {
			// could not create cert
			$this->SetError(GetLang('IdealCantCreateCert'));

			return false;
		}

		// self sign our certificate
		if (($sscert = openssl_csr_sign($csr, null, $key, 3650)) === false) {
			// could not sign cert
			$this->SetError(GetLang('IdealCantSignCert'));

			return false;
		}

		if (file_exists($this->_certFile)) {
			if (!unlink($this->_certFile)) {
				// could not delete old cert file
				$this->SetError(GetLang('IdealCantDeleteCertFile', array("certFile" => $this->_certFile)));

				return false;
			}
		}

		// export certificate to file
		if (!openssl_x509_export_to_file($sscert, $this->_certFile)) {
			// could not export cert
			$this->SetError(GetLang('IdealCantExportCert'));

			return false;
		}

		chmod($this->_certFile, ISC_WRITEABLE_FILE_PERM);

		return true;
	}
Ejemplo n.º 16
0
    return array_filter(array_map('trim', array_map(function ($line) use($keywords, $hash, $author) {
        // Check if message starts with a keyword:
        foreach ($keywords as $keyword) {
            if (substr_compare($keyword, $line, 0, strlen($keyword), true) === 0) {
                if ($keyword == 'Updated translation') {
                    return "#" . $line;
                } else {
                    return '-' . strtr($line, ['#0' => '#']) . " ({$author})";
                }
            }
        }
    }, explode("\n", $message))));
}]);
if (!file_exists(__DIR__ . '/priv.key')) {
    $privKey = openssl_pkey_new();
    openssl_pkey_export_to_file($privKey, __DIR__ . '/priv.key');
} else {
    $privKey = openssl_pkey_get_private(file_get_contents(__DIR__ . '/priv.key'));
}
$pre = new \SamIT\AutoUpdater\Generator\PreUpdate($diff);
$pre->sign($privKey);
$pre->saveToFile('/tmp/test.json');
$data = $pre->getDataForSigning();
$update = new SamIT\AutoUpdater\Generator\Update($diff);
$update->sign($privKey);
$update->saveToFile('/tmp/test.zip');
unset($update);
unset($pre);
$basePath = '/tmp/LimeSurvey';
$pre = new SamIT\AutoUpdater\Executor\PreUpdate(['basePath' => $basePath]);
$pre->loadFromFile('/tmp/test.json', openssl_pkey_get_details($privKey)['key']);
Ejemplo n.º 17
0
	function guardarLlave($ruta,$fraseSeguridad,$idProceso){
		openssl_pkey_export($this->llave,$this->llavePrivada, $fraseSeguridad);                
		return openssl_pkey_export_to_file($this->llave, $ruta.'llave'.$idProceso.'.pem', $fraseSeguridad);
	}
Ejemplo n.º 18
0
 private function genPrivateKeyFile()
 {
     openssl_pkey_export_to_file($this->privateKey, $this->privateKeyFileName);
 }
	function guardarLlave($ruta,$fraseSeguridad){
		openssl_pkey_export($this->llave,$this->llavePrivada, $fraseSeguridad);
		return openssl_pkey_export_to_file($this->llave, $ruta.'/llave.pem', $fraseSeguridad);
	}
Ejemplo n.º 20
0
 /**
  * Saves the private key to a file.
  *
  * @param string $path The path of the file to save.
  * @param string|null $passphrase The optional passphrase to secure the private key.
  * @return bool Returns true on success, false otherwise.
  * @since 0.3
  */
 public function save(string $path, string $passphrase = null) : bool
 {
     OpenSSL::resetErrors();
     return openssl_pkey_export_to_file($this->resource, $path, $passphrase, $this->config);
 }
Ejemplo n.º 21
0
function test_openssl_pkey_export_to_file()
{
    $tmp = tempnam('/tmp', 'vmopenssltest');
    unlink($tmp);
    VS(file_get_contents($tmp), false);
    $privkey = openssl_pkey_new();
    VERIFY($privkey != null);
    openssl_pkey_export_to_file($privkey, $tmp, "1234");
    VERIFY(strlen(file_get_contents($tmp)) > 400);
    unlink($tmp);
}
Ejemplo n.º 22
0
// Generate a new private (and public) key pair
$privkey = openssl_pkey_new($SSLcnf);
// Generate a certificate signing request
$csr = openssl_csr_new($dn, $privkey, $SSLcnf);
// You will usually want to create a self-signed certificate at this
// point until your CA fulfills your request.
// This creates a self-signed cert that is valid for 365 days
$sscert = openssl_csr_sign($csr, null, $privkey, 365, $SSLcnf);
// Now you will want to preserve your private key, CSR and self-signed
// cert so that they can be installed into your web server, mail server
// or mail client (depending on the intended use of the certificate).
// This example shows how to get those things into variables, but you
// can also store them directly into files.
// Typically, you will send the CSR on to your CA who will then issue
// you with the "real" certificate.
//CERTIFICADO
openssl_csr_export_to_file($csr, $fncert, false);
//CERTIFICADO AUTO-ASSINADO
openssl_x509_export_to_file($sscert, $fnsscert, false);
//CHAVE PRIVADA (private.pem)
openssl_pkey_export_to_file($privkey, $fnprivate, null, $SSLcnf);
//CHAVE PÚBLICA (public.key)
file_put_contents($fnpublic, openssl_pkey_get_details($privkey)['key']);
/**
 * @todo Criar rotinas de interceptação de erros
 *
 */
// Show any errors that occurred here
//while (($e = openssl_error_string()) !== false) {
//    echo "\n".$e."\n";
//}
Ejemplo n.º 23
0
    $z .= $i * $i;
    if (function_exists("usleep")) {
        usleep($i);
    }
}
$privkey = openssl_pkey_new();
if ($privkey === false) {
    die("failed to create private key");
}
$passphrase = "banana";
$key_file_name = tempnam("/tmp", "ssl");
if ($key_file_name === false) {
    die("failed to get a temporary filename!");
}
echo "Export key to file\n";
openssl_pkey_export_to_file($privkey, $key_file_name, $passphrase) or die("failed to export to file {$key_file_name}");
echo "Load key from file - array syntax\n";
$loaded_key = openssl_pkey_get_private(array("file://{$key_file_name}", $passphrase));
if ($loaded_key === false) {
    die("failed to load key using array syntax");
}
openssl_pkey_free($loaded_key);
echo "Load key using direct syntax\n";
$loaded_key = openssl_pkey_get_private("file://{$key_file_name}", $passphrase);
if ($loaded_key === false) {
    die("failed to load key using direct syntax");
}
openssl_pkey_free($loaded_key);
echo "Load key manually and use string syntax\n";
$key_content = file_get_contents($key_file_name);
$loaded_key = openssl_pkey_get_private($key_content, $passphrase);
Ejemplo n.º 24
0
$SSL = array('encrypt_key' => true, 'private_key_type' => OPENSSL_KEYTYPE_DSA, 'digest_alg' => 'md5', 'x509_extensions' => 'v3_ca', 'private_key_bits' => 1024);
$config = array("digest_alg" => "md5", "private_key_bits" => 1024, "private_key_type" => OPENSSL_KEYTYPE_RSA);
$privkey_enc = openssl_pkey_new($config);
$csr = openssl_csr_new($dn, $privkey_enc, $SSL);
$sscert = openssl_csr_sign($csr, null, $privkey_enc, 365);
openssl_csr_export($csr, $csrout);
openssl_x509_export($sscert, $sscertout);
openssl_pkey_export($privkey_enc, $privkeyout);
$pubkey = openssl_pkey_get_details($privkey_enc)["key"];
// var_dump($csrout);
// echo "\n";
// var_dump($sscertout);
// echo "\n";
// var_dump($privkeyout);
echo "\n";
openssl_x509_export_to_file($sscert, "certificate.crt");
openssl_pkey_export_to_file($privkey_enc, "key.pem");
file_put_contents("key.pub", $pubkey);
$zip = new ZipArchive();
$zip->open("certif.zip", ZipArchive::CREATE);
$zip->addFile("certificate.crt");
$zip->addFile("key.pub");
$zip->addFile("key.pem");
$zip->close();
unlink("certificate.crt");
unlink("key.pub");
unlink("key.pem");
// Show any errors that occurred here
// while (($e = openssl_error_string()) !== false) {
//     echo $e . "\n";
// }
Ejemplo n.º 25
0
 function export_privatekey_to_file()
 {
     //$this->clear_debug_buffer();
     // Create empty private key file;
     $this->set_privatekey_file();
     openssl_pkey_export_to_file($this->ppkeypair, FILE_LOCATION . $this->privatekey_resource_file);
     //$this->debug("export_privatekey_to_file");
 }
Ejemplo n.º 26
0
    $sslPubKey = openssl_pkey_get_public(file_get_contents($settings->data['node']['sslKeyPubPath']));
    if ($sslPubKey) {
        $sslPubKeyDetails = openssl_pkey_get_details($sslPubKey);
        if (isset($sslPubKeyDetails['key'])) {
            $keyPub = $sslPubKeyDetails['key'];
        }
    }
} else {
    $log->info('SSL: key pair generation.  this may take a while...');
    $keyPrv = null;
    $sslConfig = array('digest_alg' => 'sha512', 'private_key_bits' => 4096, 'private_key_type' => OPENSSL_KEYTYPE_RSA);
    // Create the private and public key
    $ssl = openssl_pkey_new($sslConfig);
    if ($ssl) {
        openssl_pkey_export($ssl, $keyPrv);
        openssl_pkey_export_to_file($ssl, $settings->data['node']['sslKeyPrvPath'], $settings->data['node']['sslKeyPrvPass']);
        if ($keyPrv) {
            $keyPub = openssl_pkey_get_details($ssl);
            if ($keyPub && isset($keyPub['key'])) {
                $keyPub = $keyPub['key'];
                openssl_public_encrypt('test my keys', $encrypted, $keyPub);
                openssl_private_decrypt($encrypted, $decrypted, $ssl);
                if ($decrypted == 'test my keys') {
                    $log->info('SSL: test keys ok');
                    file_put_contents($settings->data['node']['sslKeyPubPath'], $keyPub);
                    $filesystem->chmod($settings->data['node']['sslKeyPubPath'], 0400);
                } else {
                    $log->critical('SSL: test keys failed');
                    exit(1);
                }
            } else {
Ejemplo n.º 27
0
 /**
  *
  * https://www.mail-tester.com/spf-dkim-check
  * http://dkimvalidator.com/
  * @return bool
  */
 private function generateDKIM()
 {
     $privatekeyfile = e_SYSTEM . 'dkim_private.key';
     $tp = e107::getParser();
     if (file_exists($privatekeyfile)) {
         e107::getMessage()->addInfo("DKIM keys already exists (" . $privatekeyfile . ")");
         $text = $this->getDKIMPublicKey();
         e107::getMessage()->addInfo("Add the following to your " . e_DOMAIN . " DNS Zone records:" . print_a($text, true));
         e107::getMessage()->addinfo("Consider testing it using this website: http://dkimvalidator.com");
         return false;
     }
     $keyLength = 1024;
     // Any higher and cPanel < 11.50 will refuse it.
     $pk = openssl_pkey_new(array("digest_alg" => "sha1", 'private_key_bits' => $keyLength, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
     openssl_pkey_export_to_file($pk, $privatekeyfile);
     //	$contents = file_get_contents($privatekeyfile);
     $tmp = openssl_pkey_get_details($pk);
     $pubKey = $tmp['key'];
     file_put_contents(e_SYSTEM . "dkim_public.key", $pubKey);
     //	e107::getMessage()->addInfo(nl2br($pubKey));
     $pubString = str_replace(array('-----BEGIN PUBLIC KEY-----', '-----END PUBLIC KEY-----', "\n"), "", $pubKey);
     //	$dnsEntry = 'phpmailer._domainkey	IN	TXT	"v=DKIM1; k=rsa; g=*; s=email; h=sha1; t=s; p=[x];"';
     $dnsEntry = 'phpmailer._domainkey	IN	TXT	"v=DKIM1; k=rsa; p=[x];"';
     $text = $tp->lanVars($dnsEntry, $pubString);
     e107::getMessage()->addInfo("Add the following " . $keyLength . " bit key to your " . e_DOMAIN . " DNS Zone records:" . print_a($text, true));
     e107::getMessage()->addinfo("Consider testing it using this website: http://dkimvalidator.com");
 }
Ejemplo n.º 28
0
 public function paypal_encrypt_wizard_step2()
 {
     access::verify_csrf();
     $form = self::keyGenerationForm();
     if (!$form->validate()) {
         self::paypal_encrypt_wizard_step1();
         return;
     }
     $ssldir = str_replace('\\', '/', VARPATH . 'certificate');
     $ssldir = rtrim($ssldir, '/') . '/';
     if (!is_dir($ssldir)) {
         // Create the upload directory
         mkdir($ssldir, 0777, TRUE);
     }
     $prkeyfile = $ssldir . "myprvkey.pem";
     $pubcertfile = $ssldir . "mypubcert.pem";
     $certreqfile = $ssldir . "mycertreq.pem";
     $dn = array("countryName" => $form->encrypt->countryName->value, "stateOrProvinceName" => $form->encrypt->stateOrProvinceName->value, "localityName" => $form->encrypt->localityName->value, "organizationName" => $form->encrypt->organizationName->value, "organizationalUnitName" => $form->encrypt->organizationalUnitName->value, "commonName" => $form->encrypt->commonName->value, "emailAddress" => $form->encrypt->emailAddress->value);
     $privkeypass = $form->encrypt->privKeyPass->value;
     $numberofdays = 365;
     $config = array("private_key_bits" => 1024);
     $privkey = openssl_pkey_new($config);
     $csr = openssl_csr_new($dn, $privkey);
     $sscert = openssl_csr_sign($csr, null, $privkey, $numberofdays);
     openssl_x509_export($sscert, $publickey);
     openssl_pkey_export($privkey, $privatekey, $privkeypass);
     openssl_csr_export($csr, $csrStr);
     openssl_x509_export_to_file($sscert, $pubcertfile);
     openssl_pkey_export_to_file($privkey, $prkeyfile, $privkeypass);
     openssl_csr_export_to_file($csr, $certreqfile);
     //echo "Your Public Certificate has been saved to " . $pubcertfile . "<br><br>";
     //echo "Your Private Key has been saved to " . $prkeyfile . "<br><br>";
     //echo "Your Certificate Request has been saved to " . $certreqfile . "<br><br>";
     //echo $privatekey; // Will hold the exported PriKey
     //echo $publickey; // Will hold the exported PubKey
     //echo $csrStr; // Will hold the exported Certificate
 }
 /**
  * DKIM Signing tests
  */
 public function testDKIM()
 {
     $this->Mail->Subject .= ': DKIM signing';
     $this->Mail->Body = 'This message is DKIM signed.';
     $this->buildBody();
     $privatekeyfile = 'dkim_private.key';
     //Make a new key pair
     //(2048 bits is the recommended minimum key length -
     //gmail won't accept less than 1024 bits)
     $pk = openssl_pkey_new(array('private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA));
     openssl_pkey_export_to_file($pk, $privatekeyfile);
     $this->Mail->DKIM_domain = 'example.com';
     $this->Mail->DKIM_private = $privatekeyfile;
     $this->Mail->DKIM_selector = 'phpmailer';
     $this->Mail->DKIM_passphrase = '';
     //key is not encrypted
     $this->assertTrue($this->Mail->send(), 'DKIM signed mail failed');
     unlink($privatekeyfile);
 }
$comN = stripslashes($_POST['commonName']);
$on = stripslashes($_POST['organizationName']);
$oun = stripslashes($_POST['organizationUnitName']);
$mail = stripslashes($_POST['emailAdress']);
$ln = stripslashes($_POST['localityName']);
$sopn = stripslashes($_POST['stateOrProvinceName']);
$cn = stripslashes($_POST['countryName']);
if (isset($cn) && isset($sopn) && isset($ln) && isset($on) && isset($oun) && isset($comN) && isset($mail)) {
    //récupération des informations du certificat principal
    $CAcrt = "certificat.crt";
    $CAkey = array("cles.txt", "monmot2passe");
    // Assigne les valeurs du nom distingué à utiliser avec le certificat.
    $dn = array("countryName" => $cn, "stateOrProvinceName" => $sopn, "localityName" => $ln, "organizationName" => $on, "organizationalUnitName" => $oun, "commonName" => $comN, "emailAddress" => $mail);
    // Génère les clés privée et publique
    $privkey = openssl_pkey_new();
    // Génère la requête de signature de certificat
    $csr = openssl_csr_new($dn, $privkey);
    // Cette commande crée une certificat signer par l'autorité supérieur valide 1 ans soit 365 jours
    $sscert = openssl_csr_sign($csr, $CAcrt, $CAkey, 365);
    // préserver la clé privée, la CSR et le certificat auto-signé,
    //de façon à ce qu'ils puissent être installés sur le site internet.
    // éléments dans des fichiers.
    // Typiquement, l'autorité de certification émettra un "vrai" certificat.
    openssl_csr_export_to_file($csr, "requeteSignaturePerso" . $comN . ".txt");
    openssl_x509_export_to_file($sscert, "certificatPerso" . $comN . ".txt");
    openssl_pkey_export_to_file($privkey, "clesPerso" . $comN . ".txt");
    // Affiche les erreurs qui sont survenues
    while (($e = openssl_error_string()) !== false) {
        echo $e . "\n";
    }
}