darthlitox
darthlitox

Reputation: 77

How i can create a self-signed certificate using phpseclib

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"; 

?>

Upvotes: 1

Views: 1028

Answers (1)

neubert
neubert

Reputation: 16792

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.

Upvotes: 1

Related Questions