How i can create a self-signed certificate using phpseclib - php

How i can create a self-signed certificate using phpseclib from a existing .csr file, only i can use a .csr file.
I've read the manual and the method use a private key, but in my assignment i only can use a .csr file.
I hope you can help me.
Here's my code:
<?php
include('File/X509.php');
include('Crypt/RSA.php');
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//This is the content of the file
$csr = file_get_contents($_FILES["file"]["name"]);
}
// create private key / x.509 cert for stunnel / website
$privKey = new Crypt_RSA();
extract($privKey->createKey());
$privKey->loadKey($privatekey);
$pubKey = new Crypt_RSA();
$pubKey->loadKey($publickey);
$pubKey->setPublicKey();
$subject = new File_X509();
$subject->loadCSR('...'); // see csr.pem
// calling setPublicKey() is unnecessary when loadCSR() is called
$issuer = new File_X509();
$issuer->setPrivateKey($privKey);
$issuer->setDN($subject->getDN());
$x509 = new File_X509();
//$x509->setStartDate('-1 month'); // default: now
//$x509->setEndDate('+1 year'); // default: +1 year
$result = $x509->sign($issuer, $subject);
echo "the stunnel.pem contents are as follows:\r\n\r\n";
echo $privKey->getPrivateKey();
echo "\r\n";
echo $x509->saveX509($result);
echo "\r\n";
?>

You need a private key, plain and simple. Otherwise, what are you going to sign it with? The signature field of an X.509 cert is mandatory.
I mean, if all you want is a public key, you don't need to bother with the X.509 overhead. You can just pony up a public key that looks like this:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----
But X.509 is more than just a public key - it's a signed public key. Technically, a CSR is, too, but CSR's are always self-signed whereas X.509 certs can be signed by anyone.

Related

phpseclib 2.0 generates different signature than any other library with same parameters

Introduction
Hello, when signing a simple string Hello World! I get a signature that is different from any other library I'm using. I already double checked padding, algorithm, key pair, hash and input text.
Code
<?php
/*
$config = array(
"digest_alg" => "sha256",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$resource = openssl_pkey_new ($config);
// Extract the private key from $res to $privKey
openssl_pkey_export($resource, $privKey);
// Extract the public key from $res to $pubKey
$pubKey = openssl_pkey_get_details($resource);
$pubKey = $pubKey["key"];
echo var_dump($privKey) . "\n" . $pubKey;
*/
//require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/autoload.php';
use phpseclib\Crypt\RSA;
$privatekey = "-----BEGIN RSA PRIVATE KEY-----
MIIJJwIBAAKCAgEAn4CD0nFHCeM3DQkCWfXuqRVlX4rbqEk43lMgEns4DnTldrSl
1oaD9YOnwGktk7MaCf80AAZv2O4a9LIfvMxBf+LshgqTOAgvr1qy9bIkn0o/BBNY
bwOTCEnbvSha6uHlexpr31aRvzj8km4uzeBusUyJaXgF8ZMcp0UmThhdYlHhWP1E
uajkbXS8/zlD2F4TVaiPgvupIoWC62PMe5QvNWjrxOYSNwiV29QVxnHt8xm5Vx1J
ET1A4uUCVnOUQ5L+zBv+BYhCHr03j6aq+Z1aKHpEsYtCQPRCJJ/+r24+yd8tMJ2u
63feVCcSOfuZTYG8Qlr5wZICuGimneeKWpauOCqmb7osVDZfY7e2xSxnbjabtVqn
i43NWB0CcXwQ4fIbHX0/JdWmLbupIhTBJDzO6CCpyE506UZJGZOu7t16FBwGVLh3
jE1nLxwIbswv7oiN9fFBP+2eebvyuEvkSwYevGc16Mh4qfnHARwhiG0aflrUbf8h
ls2NrvCRTm7mRIjCBZe8rM7VWyZbUaA8DI8NE3/PnwjvRWLdmEqM2ShVBuDnDpeD
x46x58B1HZqeGx7HwfL/x/fSRG3uvBAG/lqKmq3o1E1gmauHm6jcnHOUftlt6nv0
xfqboScJYVgPkNT0l3rzKUtNwI3Bh0X/Yhy4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l9DTSFOhWa9ReUwYOqVMCAwEAAQ==
-----END PUBLIC KEY-----
";
$rsa = new RSA();
$rsa->loadKey($privatekey);
$rsa->loadKey($publicKey);
$rsa->setHash('sha256');
$rsa->setMGFHash('sha256'); // Added to see if it made a difference. It made no difference
//$rsa->setSaltLength($sLen)
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1); // Added to see if it made a difference. It made no difference
$rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
$plaintext = 'Hello World!';
$signature = $rsa->sign($plaintext);
$rsa->verify($plaintext, $signature);
echo base64_encode($signature);
?>
Output vs expected output
Output: Zhy04W5K+Xjhd3isDi3rlqpUgGAmcTKpW7HEPQiG8eIaxqPVqOilw60zOcS1GDuPn2b5Z1UWyvBNbw3r5fK9JSxAXCGFtbe/Fd8nGtAsCe9RW9oQ14OCwpuqWFJwADdax0GAh0KC/2JpmHYu+GG8IfESgG4NPxwe36r861jdIW9icsmcRUQOpfCkIsKClbwBhS74oIQAmbxMl23hNqzue6I7+onlZxNqnVH1XLPsMZghx1CkkpVGnSm6bHmiz01AFTF9U5oHto5MLLy1UMIhFDOFOxNHwC4ISK8kC8vnfUkm3nM3GQMD+yvDYPKLse0dYBPUcmFwiErSOkG8guA5IG4nWCkM2V5GpBHPwsGFpckjKOUvsuq+8g3ILqkW5IZSBUDaTSsHUd0CxD05DzZOGOBQ5Lhm3vMm2kbO5uwlTYbZX5deLJLOJivCip56CGX4GpAfT/VRctLyl5NL2CwVE3zUKMTnOj/NLoU7Liqw4WaYKekB2vTCUWcse8mdX1ZiUNxW3EHiXiEGB1yzVxPE0QaLdcfK3pyVVpkd5cxHOdXI5Zg/5RkADYiueyO/1oIObzHPEcAvdoj5fxW5XKnFPux6KzjWdqnqVyZXKNSZquJodn0408n2NGLrEukOVlMaixnNgvj7lmHtz/UlN0FNRzCHwVDl4q3uOiVPfRmj+28=
Expected output: J8iGPq9MWUHnzHYJqNE3y/o41uZXTdr+JGOl7YN06qIv+vbylgL367Y8B0jA/LYPcPIJDpUs991DdHEgFAE/+JkVYcrKZpmGXSFvR3RWaTe3DQZMoeD07iaOElJXVn6XBWbU77hCDUMkWXwWHbH9Ybs9BDyq8VHCrhHXgo4zyRNHB+Hb4LLVPyFCv+nQ8d6wCbY14ecyMiL5xS27g78aAg+87uTaq/naLPiSUftKiq0/ih9/Jk6IxrSLsfF4XRD2uAe5jruUMe+wZmzzYeS1syl1nto2FX/28k/z2c8Bt1Rr7nl4E6uiEKO2jYknBkwvJ2MVmbiANpeal534GRvBWaHvTGU/kZa4hEjDkRbZJ/byvLIOMrafoCQfmHYVBLS1OkVEraa34LIqla38VAV7QQGtUrq4ehYsJ16daacysCkJcuvyYz0qNoSvBV9Knh727eEbkLHrYkjf7LjYvWkVXt82AwdohzlnbQb/Ge1BhR+tV0jmC5ztpHE6xzRqkjuNU3mYKjE/Jp+udKokNXcPZcbCrFhA8MY6ay/ldy8ySYl3vTdzE0d8FzIVn/z8fBJme/nCDLeP8/bRja+dpwKwWO0c9k/cyKs0M0YEyZ/PF/CYm/sPBMZHFY4cJacVqrkbnFgEWSAnEJ8SLCqLNXKQR/4hOhlC9sF3asMCkGszrgc=
Additional details
I'm sure I'm using:
RSA
SHA256
PKCS1
Hello World! as input text
You can check using openssl or 8gwifi RSA Signature/Generation & Validation (make sure you paste the keys provided and change the signature algorithm to SHA256withRSA)
Found the problem. When loading the keys you can't load both. You need to load the one you need, do whatever operation you need and then load the other one for the next operation.

problem with PHP RSA encryption using public key return nothing

I have problem with $public_key in RSA encryption
and i receive empty result no error
I am using phpseclib
Example:
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$plaintext = 'test test';
$public_key = '-----BEGIN CERTIFICATE-----
MIIGQjCCBSqgAwIBAgIQNW5duJ7xtvmwd5qObmTdljANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQG
EwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVt
IENlc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encrypt($plaintext));
but if I change key to this one:
$rsa->loadKey('-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SdPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB
-----END PUBLIC KEY-----');
than it is working.
What is wrong with first key ?
Thanks for any help
The first key isn't a key - it's an X.509 cert. To encrypt something with the public key contained within an X.509 cert you'd need to use File_X509. Something like this (untested):
<?php
include('File/X509.php');
$x509 = new File_X509();
$x509->loadX509('...');
$rsa = $x509->getPublicKey();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);
echo $ciphertext;

how make signature by private key and check it by public key in php

I have a RSA private key and a RSA public key.
both rsa keys are in xml version ( <RSAKeyValue><Modulus>.... );
I need to make a PKCS8 signature from private key and test it by publik key in php
I used this snippet for making signature:
$content = "test string";
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->loadKey(file_get_contents("private.txt"));
$pem_format = $rsa->getPrivateKey();
$pvk_res = openssl_get_privatekey($pem_format);
$sig = '';
openssl_sign($content , $sig, $pvk_res, OPENSSL_ALGO_SHA1);
$signature = base64_encode($sig);
is this right way for making signature ??
now how use public key to test accuracy of signature ??
PKCS8 concerns key formats - not signatures.
Also, I see you're using phpseclib to convert the key to pem and then using openssl. Why not just use phpseclib for everything? At that point you could use this example:
http://phpseclib.sourceforge.net/rsa/examples.html#sign,sign2
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
//$rsa->setPassword('password');
$rsa->loadKey('...'); // private key
$plaintext = '...';
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
$signature = $rsa->sign($plaintext);
$rsa->loadKey('...'); // public key
echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified';
?>

Phpseclib KeyUsage

Default certificate file created by PhpSecLib has keyUsage set to: All rules of applications. How could I set keyUsage to digitalSignature that Windows Crypto Shell will show: Ensures the Identity of a remote computer
EDIT
Here is my code:
<?php
include('File/X509.php');
include('Crypt/RSA.php');
$c = $_POST['csr'];
$CAPrivKey = new Crypt_RSA();
$CAPrivKey->setPassword('[...]');
$CAPrivKey->loadKey("-----BEGIN RSA PRIVATE KEY-----
[...]
-----END RSA PRIVATE KEY-----
");
$issuer = new File_X509();
$issuer->setPrivateKey($CAPrivKey);
$issuer->loadX509("-----BEGIN CERTIFICATE-----
[...]
-----END CERTIFICATE-----
");
$subject = new File_X509();
$subject->loadCSR($c);
$x509 = new File_X509();
$x509->setStartDate('-1 month');
$x509->setEndDate('+1 year');
$x509->setSerialNumber('125');
$result = $x509->sign($issuer, $subject);
$x509->loadX509($result);
$x509->setExtension('id-ce-keyUsage', array_merge($x509->getExtension('id-ce- keyUsage'), array('digitalSignature')));
$result = $x509->sign($issuer, $x509);
//echo $x509->saveX509($result);
header('Content-Type: application/x-x509-ca-cert');
header("Content-Disposition: attachment; filename='ssl.cer'");
echo $x509->saveX509($result);
?>
Unless you're resigning a cert you'll need to create your cert by doing an $x509->sign() first. Then you'll need to reload that cert, set the extension, resign it and save it. eg.
<?php
include('File/X509.php');
include('Crypt/RSA.php');
$privKey = new Crypt_RSA();
$privKey->loadKey('...');
$pubKey = new Crypt_RSA();
$pubKey->loadKey($privKey->getPublicKey());
$pubKey->setPublicKey();
$subject = new File_X509();
$subject->setDNProp('id-at-organizationName', 'demo cert');
$subject->setPublicKey($pubKey);
$issuer = new File_X509();
$issuer->setPrivateKey($privKey);
$issuer->setDN($subject->getDN());
$x509 = new File_X509();
//$x509->makeCA();
$x509->setSerialNumber('1');
$result = $x509->sign($issuer, $subject);
$x509->loadX509($result);
$x509->setExtension('id-ce-keyUsage', array('digitalSignature'));
//$x509->setExtension('id-ce-keyUsage', array_merge($x509->getExtension('id-ce-keyUsage'), array('digitalSignature')));
$result = $x509->sign($issuer, $x509);
echo $x509->saveX509($result);
?>
It'd be nice if the whole resigning thing was unnecessary but whatever. I'll see if I can get the phpseclib author to make some revisions to it at some point.
Can you post your cert? Because when I use your program it's totally not doing that for me. My code:
<?php
include('File/X509.php');
include('Crypt/RSA.php');
$c = '-----BEGIN CERTIFICATE REQUEST-----
MIIBVjCBwgIAMB4xHDAaBgNVBAoME3BocHNlY2xpYiBkZW1vIGNlcnQwgZ0wCwYJKoZIhvcNAQEB
A4GNADCBiQKBgQDF+1/N2DwvdkhoHsLq8LnH99AEGVOGpooSpbPCewbuZeqr/Djb9ySPar2PLySo
Y+kB2QAbxUgpO/57IpWIabQ9jDFIznqLCcLzXKiKOWnMv4KMf55yJ6pwlqoTbUPgyQ67CRAfjcaD
W9VQ/TzdKahdxLFPBAEIEpEX23YpLhTLNQIDAQABMAsGCSqGSIb3DQEBBQOBgQALjJE4OygjvLm0
rzFyMPvAo7Ux6z5qTOi//HQzzmjNun7MV09GTfZgcYeWvuLosJXcn7CPALF5FqHWePs98WioTA7K
WsvdZzm+yJ5UcmzdJ/Jq9X8o1KTsMELN0SQwiNk502a1wbiXotF4OgCsjSdno96PCV9VSF4w69HM
1eXfvg==
-----END CERTIFICATE REQUEST-----';
$CAPrivKey = new Crypt_RSA();
$CAPrivKey->loadKey('-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----');
$issuer = new File_X509();
$issuer->setPrivateKey($CAPrivKey);
$issuer->loadX509("-----BEGIN CERTIFICATE-----
MIIDITCCAoqgAwIBAgIQT52W2WawmStUwpV8tBV9TTANBgkqhkiG9w0BAQUFADBM
MQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkg
THRkLjEWMBQGA1UEAxMNVGhhd3RlIFNHQyBDQTAeFw0xMTEwMjYwMDAwMDBaFw0x
MzA5MzAyMzU5NTlaMGgxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlh
MRYwFAYDVQQHFA1Nb3VudGFpbiBWaWV3MRMwEQYDVQQKFApHb29nbGUgSW5jMRcw
FQYDVQQDFA53d3cuZ29vZ2xlLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkC
gYEA3rcmQ6aZhc04pxUJuc8PycNVjIjujI0oJyRLKl6g2Bb6YRhLz21ggNM1QDJy
wI8S2OVOj7my9tkVXlqGMaO6hqpryNlxjMzNJxMenUJdOPanrO/6YvMYgdQkRn8B
d3zGKokUmbuYOR2oGfs5AER9G5RqeC1prcB6LPrQ2iASmNMCAwEAAaOB5zCB5DAM
BgNVHRMBAf8EAjAAMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwudGhhd3Rl
LmNvbS9UaGF3dGVTR0NDQS5jcmwwKAYDVR0lBCEwHwYIKwYBBQUHAwEGCCsGAQUF
BwMCBglghkgBhvhCBAEwcgYIKwYBBQUHAQEEZjBkMCIGCCsGAQUFBzABhhZodHRw
Oi8vb2NzcC50aGF3dGUuY29tMD4GCCsGAQUFBzAChjJodHRwOi8vd3d3LnRoYXd0
ZS5jb20vcmVwb3NpdG9yeS9UaGF3dGVfU0dDX0NBLmNydDANBgkqhkiG9w0BAQUF
AAOBgQAhrNWuyjSJWsKrUtKyNGadeqvu5nzVfsJcKLt0AMkQH0IT/GmKHiSgAgDp
ulvKGQSy068Bsn5fFNum21K5mvMSf3yinDtvmX3qUA12IxL/92ZzKbeVCq3Yi7Le
IOkKcGQRCMha8X2e7GmlpdWC1ycenlbN0nbVeSv3JUMcafC4+Q==
-----END CERTIFICATE-----");
$subject = new File_X509();
$subject->loadCSR($c);
$x509 = new File_X509();
$x509->setStartDate('-1 month');
$x509->setEndDate('+1 year');
$x509->setSerialNumber('125');
$result = $x509->sign($issuer, $subject);
$x509->loadX509($result);
$x509->setExtension('id-ce-keyUsage', array('digitalSignature'));
//$x509->setExtension('id-ce-keyUsage', array_merge($x509->getExtension('id-ce-keyUsage'), array('digitalSignature')));
$result = $x509->sign($issuer, $x509);
//echo $x509->saveX509($result);
header('Content-Type: application/x-x509-ca-cert');
header("Content-Disposition: attachment; filename='ssl.cer'");
echo $x509->saveX509($result);
Screenshot:
The cert itself:
-----BEGIN CERTIFICATE-----
MIICCzCCAXagAwIBAgIDMTI1MAsGCSqGSIb3DQEBBTBoMQswCQYDVQQGEwJVUzET
MBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxQNTW91bnRhaW4gVmlldzETMBEG
A1UEChQKR29vZ2xlIEluYzEXMBUGA1UEAxQOd3d3Lmdvb2dsZS5jb20wIhgPMjAx
MjExMjUwNzE0MTJaGA8yMDEzMTIyNTA3MTQxMlowHjEcMBoGA1UECgwTcGhwc2Vj
bGliIGRlbW8gY2VydDCBnTALBgkqhkiG9w0BAQEDgY0AMIGJAoGBAMX7X83YPC92
SGgewurwucf30AQZU4amihKls8J7Bu5l6qv8ONv3JI9qvY8vJKhj6QHZABvFSCk7
/nsilYhptD2MMUjOeosJwvNcqIo5acy/gox/nnInqnCWqhNtQ+DJDrsJEB+NxoNb
1VD9PN0pqF3EsU8EAQgSkRfbdikuFMs1AgMBAAGjDzANMAsGA1UdDwQEAwIHgDAL
BgkqhkiG9w0BAQUDgYEAMtVKyBpbvD2txhlRtA3VHoL1Zp9E7CN/EqFxpAG7bwZT
8D1gifeff4tGH0zkbGvv+5kb5exBZ+PhGsaaHVZoBQVO33Rkr32rfMeMa7PYb76L
i+f0mOp1QfPbrQuvT/uJx8AUv/Owsk5zLyE7JznsvYQ7VeGARRAike2ThHGcZQ8=
-----END CERTIFICATE-----
So like I said, it's working just fine for me.
Maybe you can post the cert you're getting when you try to run it? Maybe you can post the CSR you're using as well?
When I tried to run your code I got a bunch of errors. Mainly due to this line:
$x509->setExtension('id-ce-keyUsage', array_merge($x509->getExtension('id-ce- keyUsage'), array('digitalSignature')));
Two problems with that:
You have spaces between id-ce- and keyUsage. Those spaces shouldn't be there.
array_merge will return NULL if getExtension returns NULL. ie. if that extension is undefined. As such what you'll need to do is this:
$x509->setExtension('id-ce-keyUsage', array('digitalSignature'));

Generate SSH keypair form PHP

I want to generate ssh keypair from php can anyone please guide me how to do it? I have tried the shell_exec but the shell asks questions so that command does not work. I would like to specify filename and path in which to put the keys after generation.
This is based on Converting an OpenSSL generated RSA public key to OpenSSH format (PHP). Thanks shevron.
<?php
$rsaKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA));
$privKey = openssl_pkey_get_private($rsaKey);
openssl_pkey_export($privKey, $pem); //Private Key
$pubKey = sshEncodePublicKey($rsaKey); //Public Key
$umask = umask(0066);
file_put_contents('/tmp/test.rsa', $pem); //save private key into file
file_put_contents('/tmp/test.rsa.pub', $pubKey); //save public key into file
print "Private Key:\n $pem \n\n";
echo "Public key:\n$pubKey\n\n";
function sshEncodePublicKey($privKey) {
$keyInfo = openssl_pkey_get_details($privKey);
$buffer = pack("N", 7) . "ssh-rsa" .
sshEncodeBuffer($keyInfo['rsa']['e']) .
sshEncodeBuffer($keyInfo['rsa']['n']);
return "ssh-rsa " . base64_encode($buffer);
}
function sshEncodeBuffer($buffer) {
$len = strlen($buffer);
if (ord($buffer[0]) & 0x80) {
$len++;
$buffer = "\x00" . $buffer;
}
return pack("Na*", $len, $buffer);
}
?>
I would use phpseclib, a pure PHP RSA implementation:
<?php
include('Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_OPENSSH);
extract($rsa->createKey());
echo "$publickey\r\n\r\n$privatekey";
?>
Sample output:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZw== phpseclib-generated-key
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp
wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5
1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh
3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2
pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX
GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il
AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF
L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k
X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl
U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ
37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0=
-----END RSA PRIVATE KEY-----
Source: http://phpseclib.sourceforge.net/rsa/examples.html#openssh
Has anybody tried this?
ssh-keygen -q -N place_your_passphrase_here -t rsa -f ~/.ssh/id_rsa
It's worked for me
Check the manpage of ssh-keygen to find out how to execute it without any prompts.
http://linux.die.net/man/1/ssh-keygen
This code uses only built-in PHP openssl functions.
It generates keys in a portable PEM format, suitable for use with most 3rd party software.
<?php
function generateRsaKeyPair(array $config = []): array
{
$config = array_merge([
'digest_alg' => 'sha512',
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
], $config);
// Create the keypair
$key = openssl_pkey_new($config);
if (!$key) {
throw new RuntimeException('Unable to generate RSA key pair');
}
// Get private key
openssl_pkey_export($key, $private);
if (!$private) {
throw new RuntimeException('Unable to extract private key');
}
// Get public key
$public = openssl_pkey_get_details($key)['key'] ?? null;
if (!$public) {
throw new RuntimeException('Unable to extract public key');
}
// Free key from memory
openssl_pkey_free($key);
// Return both keys
return compact('public', 'private');
}

Categories