Skip to content

Certificate Authority Controllers

AuthenticodeController

app/Http/Controllers/Admin/AuthenticodeController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyCertificateRequest;
use App\Http\Requests\StoreCertificateRequest;
use App\Http\Requests\UpdateCertificateRequest;
use App\Cert;


class AuthenticodeController extends Controller
{
    public function index()
    {
        abort_unless(\Gate::allows('certificate_access'), 403);

        $certsNumber = Cert::all()->count();
        $certs = Cert::all();

        $certs_status_blank = Cert::where('status', '=', null)->count();
        $certs_status_valid = Cert::where('status', '=', 'Valid')->count();
        $certs_status_expiring = Cert::where('status', '=', 'Expiring')->count();
        $certs_status_expired = Cert::where('status', '=', 'Expired')->count();
        $certs_status_revoked = Cert::where('status', '=', 'Revoked')->count();
        //dd($certs);
        return view('admin.certs.index', compact('certs',
                                                'certsNumber',
                                                'certs_status_blank',
                                                'certs_status_valid',
                                                'certs_status_expiring',
                                                'certs_status_expired',
                                                'certs_status_revoked'));
    }

    public function create()
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        return view('admin.certs.create');
    }

    public function store(StoreCertificateRequest $request)
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        $cert = Cert::create($request->all());

        return redirect()->route('admin.certs.index');
    }

    public function edit(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        return view('admin.certs.edit', compact('cert'));
    }

    public function update(UpdateCertificateRequest $request, Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        $cert->update($request->all());

        return redirect()->route('admin.certs.index');
    }

    public function show(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_show'), 403);

        return view('admin.certs.show', compact('cert'));
    }

    public function destroy(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_delete'), 403);

        $cert->delete();

        return back();
    }

    public function massDestroy(MassDestroyCertificateRequest $request)
    {
        Cert::whereIn('id', request('ids'))->delete();

        return response(null, 204);
    }
}

CertificatesController

app/Http/Controllers/Admin/CertificatesController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyCertificateKeyPair;
use App\Http\Requests\StoreCertificateKeyPair;
use App\Http\Requests\UpdateCertificate;
use App\Exceptions\WrongCaKeyPasswordException;
use Spatie\SslCertificate\SslCertificate;
//use RealRashid\SweetAlert\Facades\Alert;
use App\Cert;
use App\Params;
use File;
use ZipArchive;
use Carbon\Carbon;

class CertificatesController extends Controller
{
    public function index()
    {
        abort_unless(\Gate::allows('certificate_access'), 403);

        $certsNumber = Cert::all()->count();
        $certs = Cert::all();

        /** Recalculate the expiry date and update */
        foreach ($certs as $cert) {

            $id = $cert->id;

            /** calculate days diff between cert and today and update DB. */
            if ($cert->validTo_time_t != null){
             $certificate = SslCertificate::createFromString($cert->publicKey);
             //$today = Carbon::today();
             $validToDate = $certificate->expirationDate();
             $expiryDate = (string)$validToDate->diffInDays(today(), false);
             $isValid = $certificate->isValid();
             $isExpired = $certificate->isExpired();

             /**  Calculate days to expire. */
              $isExpiringInterval = $validToDate->copy()->subDays(60);
              $isExpiring = today()->isBetween($isExpiringInterval, $validToDate);

             /** Update diff in day. */
             Cert::where('id', $id)->update(['expiryDate' => $expiryDate]);
           }

           if (empty($cert->publicKey)){

               $status = null;
               Cert::where('id', $id)->update(['status' => $status]);

           } elseif ($isExpired === true) {

               $status = 'Expired';
               Cert::where('id', $id)->update(['status' => $status ]);

             /** Ones cert is expired, it is deleted so that it is not scan with expiry check script. */
             FILE::delete(storage_path('archives/keypairs/' . $id . '.zip'));
             FILE::delete(storage_path('archives/monitor/' . $id . '.cer'));
             FILE::delete(storage_path('archives/p12/' . $id . '.p12'));

            } elseif ($isExpiring === true && $cert->status != 'Revoked'){

                $status = 'Expiring';
                Cert::where('id', $id)->update(['status' => $status]);

            } elseif ($cert->status === 'Revoked'){

                $status = 'Revoked';
                Cert::where('id', $id)->update(['status' => $status]);

            } elseif ($isValid === true){

               $status = 'Valid';
               Cert::where('id', $id)->update(['status' => $status]);

             } else {
               $status = $cert->status; 
               Cert::where('id', $id)->update(['status' => $status]);
            }
           }

        /** Chart */
        $certs_status_blank = Cert::where('status', '=', null)->count();
        $certs_status_valid = Cert::where('status', '=', 'Valid')->count();
        $certs_status_expiring = Cert::where('status', '=', 'Expiring')->count();
        $certs_status_expired = Cert::where('status', '=', 'Expired')->count();
        $certs_status_revoked = Cert::where('status', '=', 'Revoked')->count();


        return view('admin.certs.index', compact('certs',
                                                'certsNumber',
                                                'certs_status_blank',
                                                'certs_status_valid',
                                                'certs_status_expiring',
                                                'certs_status_expired',
                                                'certs_status_revoked' ));
    }

    public function create()
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        $params = Params::all();

        return view('admin.certs.new-cert.create', compact('params'));
    }

    public function store(StoreCertificateKeyPair $request)
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

            /** Separate CN and SANs. */
            $commonName = explode(";", $request->subjectCommonName);
            $subjectCommonName = $commonName[0];
            $extensionsSubjectAltName = explode(",", ("DNS:".implode(",DNS:", $commonName)));
            $extensionsSubjectAltName = implode(",", $extensionsSubjectAltName);

            /** Configuration file. */
            $config = '/usr/lib/ssl/openssl.cnf';

            /** Data needed to populate the certificate signed by this CA. email can´t be empty so if it is empty "emailAddress" is not included. */
            if($request->email != ''){
                  $dn = array(
                     "countryName" => 'ES',
                     "stateOrProvinceName" => 'Madrid',
                     "localityName" => 'Madrid',
                     "organizationName" => $request->subjectOrganization,
                     "organizationalUnitName" => $organizationUnitName,
                     "commonName" => $subjectCommonName,
                     "emailAddress" => $request->email
                     );
             } else {
                  $dn = array(
                     "countryName" => 'ES',
                     "stateOrProvinceName" => 'Madrid',
                     "localityName" => 'Madrid',
                     "organizationName" => $request->subjectOrganization,
                     "organizationalUnitName" => $organizationUnitName,
                     "commonName" => $subjectCommonName
                     //"emailAddress" => null
                     );
               }

            /** Clean DNS entries. */
            shell_exec("sudo /opt/subjectAltNameRemoval.sh 2>&1"); /** Clear DNS entries script. */
            $configFile = file_get_contents($config);
            $configFile = str_replace("DNS:", $extensionsSubjectAltName, $configFile); /** Do replacements. */
            file_put_contents($config, $configFile);
            unset($configFile);

            /** Arguments to be passed to the CSR. */
            $configArgs = array(
                'config' => $config,
                'encrypt_key' => false,
                'private_key_type' => OPENSSL_KEYTYPE_RSA,
                'subjectAltName' => $request->extensionsSubjectAltName,
                'digest_alg' => $request->signatureTypeSN );

            /** Generate REQ and his corresponding Private Key. */
            $reqgen = openssl_csr_new($dn, $keygen, $configArgs);

            /** Export Private Key to string and save it to disk. */
            openssl_pkey_export($keygen, $privateKey);

            /** Export CSR to string and save it to disk. */
            openssl_csr_export($reqgen, $certificateServerRequest);

            /** Signing CSR. Location of CA Pub/Priv certificates. */
            $cacert = file_get_contents('/opt/ca/cacert.pem');
            $pkeyid = array(file_get_contents('/opt/ca/private/cakey.pem'), $request->password );
            $configArgs = array(
                    'config' => $config,
                    'encrypt_key' => false,
                    'private_key_bits' => (int)$request->keyLength,
                    'private_key_type' => OPENSSL_KEYTYPE_RSA,
                    'digest_alg' => $request->signatureTypeSN,
                    'x509_extensions' => $request->extensionsExtendedKeyUsage);

            /** Insert serial number. */
            $serialNumber = random_int(160000000001, 170000000001);

            /** Sign Certificate Server Request. */
            $certgen = openssl_csr_sign($certificateServerRequest , $cacert, $pkeyid, $request->validityPeriod, $configArgs, $serialNumber);

            /** Export signed certificate to string variable and save it to disk. */
            openssl_x509_export($certgen, $publicKey);

            /** Clean SAN DNS entries. */
            shell_exec("sudo /opt/subjectAltNameRemoval.sh 2>&1");

            /** Parse certificate data. */
            $certParser = openssl_x509_parse($publicKey);

            /** Include certificate parse data in request.  */
            $request['subjectCommonName'] = $certParser['subject']['CN'];
            $request['subjectContry'] = $certParser['subject']['C'];
            $request['subjectState'] = $certParser['subject']['ST'];
            $request['subjectOrganization'] = $certParser['subject']['O'];
            $request['subjectOrganizationUnit'] = $certParser['subject']['OU'];
            $request['hash'] = $certParser['hash'];
            $request['issuerCN'] = $certParser['issuer']['CN'];
            $request['issuerOrganization'] = $certParser['issuer']['O'];
            $request['issuerOrganizationUnit'] = $certParser['issuer']['OU'];
            $request['version'] = $certParser['version'];
            $request['serialNumber'] = $serialNumber;
            //$request['serialNumberHex'] = $serialNumberHex;
            $request['validFrom'] = $certParser['validFrom'];
            $request['validTo'] = $certParser['validTo'];
            $request['validFrom_time_t'] = $certParser['validFrom_time_t'];
            $request['validTo_time_t'] = $certParser['validTo_time_t'];
            $request['signatureTypeSN'] = $certParser['signatureTypeSN'];
            $request['signatureTypeLN'] = $certParser['signatureTypeLN'];
            $request['signatureTypeNID'] = $certParser['signatureTypeNID'];
            $request['purposes'] = null; // to be implemented.
            $request['extensionsBasicConstraints'] = $certParser['extensions']['basicConstraints'];
            $request['extensionsKeyUsage'] = $certParser['extensions']['keyUsage'];
            $request['extensionsExtendedKeyUsage'] = $certParser['extensions']['extendedKeyUsage'];
            $request['extensionsSubjectKeyIdentifier'] = $certParser['extensions']['subjectKeyIdentifier'];
            $request['extensionsAuthorityKeyIdentifier'] = $certParser['extensions']['authorityKeyIdentifier'];
            $request['extensionsSubjectAltName'] = $certParser['extensions']['subjectAltName'];
            $request['extensionsCrlDistributionPoints'] = $certParser['extensions']['crlDistributionPoints'];
            $request['certificateServerRequest'] = $certificateServerRequest;
            $request['publicKey'] = $publicKey;
            $request['privateKey'] = $privateKey;
            $request['status'] = 'Valid';
            $request['p12'] = null;

            /** Convert dates. */
            $validTo_time_t = date(DATE_RFC2822, $certParser['validTo_time_t']);
            $expiryDate = Carbon::parse(Carbon::now())->diffInDays($validTo_time_t);
            $request['expiryDate'] = $expiryDate;

            $cert = Cert::create($request->all());
            $cert->save();

            $cert = Cert::where('subjectCommonName', $subjectCommonName)->get()->last();

            file_put_contents(storage_path('archives/tmp/' . $cert->id . '.key'), $privateKey);
            file_put_contents(storage_path('archives/tmp/' . $cert->id .'.cer'), $publicKey);
            file_put_contents(storage_path('archives/tmp/' . $cert->id . '.csr'), $certificateServerRequest);

            /** If Monitor check enabled, include in /opt/certmon/ json.
             * Possible solution is to trigger the e-mail or just include the json data in the files.
            */


            /** end include in certmon */

            file_put_contents(storage_path('archives/monitor/' . $cert->id . '.cer'), $publicKey);

            /** Zip the .cer and .key saved in storage_path/tmp and move it to storage_path/archives. then, delete files. */
            $zipFile = $cert->id . '.zip';

            $zip = new ZipArchive();
            $path = storage_path('archives/keypairs/');
            $zip->open($path . $zipFile, ZipArchive::CREATE);
            //$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
            $files = File::files(storage_path('archives/tmp/'));

            foreach ($files as $name => $file)
            {
                /** Skipping all subfolders */
                if (!$file->isDir()) {
                    $filePath = $file->getRealPath();

                    /** Extracting filename with substr/strlen */
                    $relativePath = '' . substr($filePath, strlen($path) -5);

                    $zip->addFile($filePath, $relativePath);
                }
            }
            $zip->close();


            File::delete(storage_path('archives/tmp/' . $cert->id . '.csr'));
            File::delete(storage_path('archives/tmp/' . $cert->id . '.cer'));
            File::delete(storage_path('archives/tmp/' . $cert->id . '.key'));

        //Alert::success('Certificate successfully created', 'Certificate keypair has been created', 'Success');
        return redirect()->route('admin.certs.index')->with('success', 'Certificate keypair created successfully.');
    }

    public function edit(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        return view('admin.certs.edit', compact('cert'));
    }

    public function update(UpdateCertificate $request, Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        /** Make a Keymatch before updating. */
        if ($request->filled(['certificateServerRequest','publicKey', 'privateKey']) && $cert->status != 'Revoked') {

            /** Check if PublicKey matches PrivateKey. */
            $keyMatches = openssl_x509_check_private_key($request->input('publicKey'), $request->input('privateKey'));

            /** Check if CSR matches PublicKey. */
                file_put_contents(storage_path('archives/tmp/') . 'csr.csr', $request->input('certificateServerRequest'));
                file_put_contents(storage_path('archives/tmp/') . 'cert.cer', $request->input('publicKey'));
                file_put_contents(storage_path('archives/tmp/') . 'key.key', $request->input('privateKey'));

                $certSHA2sum = shell_exec("openssl x509 -in archives/tmp/cert.cer -pubkey -noout -outform pem | sha256sum 2>&1");
                $csrSHA2sum = shell_exec("openssl req -in archives/tmp/csr.csr -pubkey -noout -outform pem | sha256sum 2>&1");

                if($certSHA2sum === $csrSHA2sum && $keyMatches === true){

                    $cert->update($request->all('certificateServerRequest'));
                    $cert->update($request->all('publicKey'));
                    $cert->update($request->all('privateKey'));
                    $cert->update($request->all('comments'));

                } else {

                    File::delete(storage_path('archives/tmp/') . 'csr.csr');
                    File::delete(storage_path('archives/tmp/') . 'cert.cer');
                    File::delete(storage_path('archives/tmp/') . 'key.key');

                    return redirect()->route('admin.certs.index')->with('error', 'Certificate and Private key don´t match');
                }

            /** Parse certificate data. */
            $certParser = openssl_x509_parse($request->input('publicKey'));
                $request['subjectCommonName'] = $certParser['subject']['CN'];
                $request['subjectContry'] = $certParser['subject']['C'];
                //$request['subjectState'] = $certParser['subject']['ST'];
                $request['subjectOrganization'] = $certParser['subject']['O'];
                //$request['subjectOrganizationUnit'] = $certParser['subject']['OU'];
                $request['hash'] = $certParser['hash'];
                $request['issuerCN'] = $certParser['issuer']['CN'];
                $request['issuerOrganization'] = $certParser['issuer']['O'];
                //$request['issuerOrganizationUnit'] = $certParser['issuer']['OU'];
                $request['version'] = $certParser['version'];
                $request['serialNumber'] = $certParser['serialNumber'];
                $request['serialNumberHex'] = $certParser['serialNumberHex'];
                $request['validFrom'] = $certParser['validFrom'];
                $request['validTo'] = $certParser['validTo'];
                $request['validFrom_time_t'] = $certParser['validFrom_time_t'];
                $request['validTo_time_t'] = $certParser['validTo_time_t'];
                $request['signatureTypeSN'] = $certParser['signatureTypeSN'];
                $request['signatureTypeLN'] = $certParser['signatureTypeLN'];
                $request['signatureTypeNID'] = $certParser['signatureTypeNID'];
                $request['purposes'] = null;
                $request['extensionsBasicConstraints'] = $certParser['extensions']['basicConstraints'];
                $request['extensionsKeyUsage'] = $certParser['extensions']['keyUsage'];
                $request['extensionsExtendedKeyUsage'] = $certParser['extensions']['extendedKeyUsage'];
                $request['extensionsSubjectKeyIdentifier'] = $certParser['extensions']['subjectKeyIdentifier'];
                $request['extensionsAuthorityKeyIdentifier'] = $certParser['extensions']['authorityKeyIdentifier'];
                $request['extensionsSubjectAltName'] = $certParser['extensions']['subjectAltName'];
                $request['extensionsCrlDistributionPoints'] = $certParser['extensions']['crlDistributionPoints'];
                $request['certificateServerRequest'] = $request->input('certificateServerRequest');
                $request['publicKey'] = $request->input('publicKey');
                $request['privateKey'] = $request->input('privateKey');
                $request['p12'] = null;

                /** Convert dates. */
                $validTo_time_t = date(DATE_RFC2822, $certParser['validTo_time_t']);
                $expiryDate = Carbon::parse(Carbon::now())->diffInDays($validTo_time_t, false); /** in days */

                $request['expiryDate'] = $expiryDate;

                /** Calculate status: Valid,Expiring, Expired. */
                if($expiryDate > 0) {
                    $request['status'] = 'Valid';
                }
                elseif($expiryDate >= 90) {
                    $request['status'] = 'Expiring';
                }
                elseif($expiryDate < 0) {
                    $request['status'] = 'Expired';
                }

                $cert->update($request->all(
                    'subjectCommonName',
                    'subjectContry',
                    //'subjectState',
                    'subjectOrganization',
                    //'subjectOrganizationUnit',
                    'hash',
                    'issuerCN',
                    'issuerOrganization',
                    //'issuerOrganizationUnit',
                    'version',
                    'serialNumber',
                    'serialNumberHex',
                    'validFrom',
                    'validTo',
                    'validFrom_time_t',
                    'validTo_time_t',
                    'expiryDate',
                    'signatureTypeSN',
                    'signatureTypeLN',
                    'signatureTypeNID',
                    'purposes',
                    'extensionsBasicConstraints',
                    'extensionsKeyUsage',
                    'extensionsExtendedKeyUsage',
                    'extensionsSubjectKeyIdentifier',
                    'extensionsSubjectAltName',
                    'extensionsSubjectAltName',
                    'extensionsCrlDistributionPoints',
                    'certificateServerRequest',
                    'publicKey',
                    'privateKey',
                    'status',
                    'p12',
                ));

        /** Include certificate to local monitor  */
        file_put_contents(storage_path('archives/monitor/' . $cert->id . '.cer'), $request->publicKey);

        /** Zip the .cer and .key saved in storage_path/tmp and move it to storage_path/archives. */
        $zipFile = $cert->id . '.zip';
        $zip = new ZipArchive();
        $path = storage_path('archives/keypairs/');

        $zip->open($path . $zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);

        //$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
        $files = File::files(storage_path('archives/tmp/'));

        foreach ($files as $name => $file)
        {
            /** Skipping all subfolders */
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();

                /** extracting filename with substr/strlen */
                $relativePath = '' . substr($filePath, strlen($path) -5);
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();

        /** Include certificate to local monitor  */
        file_put_contents(storage_path('archives/monitor/' . $cert->id . '.cer'), $request->publicKey);

        File::delete(storage_path('archives/tmp/') . 'csr.csr');
        File::delete(storage_path('archives/tmp/') . 'cert.cer');
        File::delete(storage_path('archives/tmp/') . 'key.key');

            return redirect()->route('admin.certs.index')->with('success','Updated successfully.');

        } elseif ($cert->status === 'Revoked'){

            return redirect()->route('admin.certs.index')->with('error','Certificate is Revoked and can´t be updated.');

        } else {
                //Alert::error('Error Updating', 'Data don´t match or has not been provided.', 'error')->persistent('close');
                return redirect()->route('admin.certs.index')->with('error','Error updating. Check if public and private key matches.');
        }
    }

    public function show(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_show'), 403);

        /** Convert dates validFrom and validTo to show them properly in view. */
        $certs = Cert::all();

        $validFrom_time_t = date(DATE_RFC2822, $cert->validFrom_time_t);
        $validTo_time_t = date(DATE_RFC2822, $cert->validTo_time_t);
        $created_at = $cert->created_at;

        return view('admin.certs.show', compact(
            'cert',
            'validFrom_time_t', 
            'validTo_time_t',
            'created_at'
        ));
    }

    public function destroy(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_delete'), 403);

        $cert->delete();
        /** Delete file from storage. This file is used by the local monitoring script */
        //Alert::success('Deleted Successfully', 'All data related to this certificate has been deleted.', 'Success');
        File::delete(storage_path('archives/monitor/' . $cert->id .'.cer'));
        File::delete(storage_path('archives/keypairs/' . $cert->id .'.zip'));

        return back();
    }

    public function massDestroy(MassDestroyCertificateKeyPair $request)
    {
        Cert::whereIn('id', request('ids'))->delete();

        return response(null, 204);
    }

}

ConverterController

app/Http/Controllers/Admin/ConverterController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Cert;

class ConverterController extends Controller
{

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $cert = Cert::where('id', $request->id)->get()->first();
        $p12Args = array(
            'friendly_name' => $cert->subjectCommonName,
            'extracerts' => storage_path('archives/','cert.ca.cer')
        );

        /** Export it to string format in order to insert it in database and to file to back it up in archives/p12/ */
        openssl_pkcs12_export($cert->publicKey, $p12String, $cert->privateKey, $request->password, $p12Args);
        openssl_pkcs12_export_to_file($cert->publicKey, storage_path('archives/p12/' . $request->id . '.p12'), $cert->privateKey, $request->password, $p12Args);

        /** Update database field 'p12' */
        Cert::where('id', $request->id)->update(['p12' => $p12String]);

        $headers = array('Content_Type: application/x-download',);
        return response()->download(storage_path('archives/p12/' . $request->id . '.p12'), $request->id . '.p12', $headers);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function Show($id)
    {
        $cert = Cert::where('id', $id)->get()->first();
        $subjectCommonName = $cert->subjectCommonName;

        if ($cert->publicKey == null OR $cert->privateKey == null){

            return redirect()->route('admin.certs.index')->with('error','Keys not found. Check if Public and Private keys exist and match.');

        } else {

            return view('admin.converter.show', compact('id', 'subjectCommonName'));
       }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        dd('Edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        dd('Update');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        dd('Destroy');
    }
}

DownloadArchiveController

app/Http/Controllers/Admin/DownloadArchiveController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;

class DownloadArchiveController extends Controller
{
    function downloadArchive($id){

            $headers = array('Content_Type: application/x-download');
            return Response::download(storage_path('archives/keypairs/' . $id . '.zip'), $id . '.zip', $headers);
    }

    function downloadCA(){

        $headers = array('Content_Type: application/x-download');
        return Response::download(storage_path('archives/cert.ca.cer'), 'cert.ca.cer', $headers);
}

    function downloadCRL(){

        $headers = array('Content_Type: application/x-download');
        return Response::download(storage_path('archives/ca-g2.crl'), 'ca-g2.crl', $headers);
    }


}

ImportController

app/Http/Controllers/Admin/ImportController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;

class ImportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
         // Code

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        return view('admin.import.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

JarSignerController

app/Http/Controllers/Admin/JarSignerController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyCertificateRequest;
use App\Http\Requests\StoreCertificateRequest;
use App\Http\Requests\UpdateCertificateRequest;
use App\Cert;

class JarSignerController extends Controller
{
    public function index()
    {
        abort_unless(\Gate::allows('certificate_access'), 403);

        $certsNumber = Cert::all()->count();
        $certs = Cert::all();
                // Chart - Certificates status.
        $certs_status_blank = Cert::where('status', '=', null)->count();
        $certs_status_valid = Cert::where('status', '=', 'Valid')->count();
        $certs_status_expiring = Cert::where('status', '=', 'Expiring')->count();
        $certs_status_expired = Cert::where('status', '=', 'Expired')->count();
        $certs_status_revoked = Cert::where('status', '=', 'Revoked')->count();
        //dd($certs);
        return view('admin.certs.index', compact('certs',
                                                'certsNumber',
                                                'certs_status_blank',
                                                'certs_status_valid',
                                                'certs_status_expiring',
                                                'certs_status_expired',
                                                'certs_status_revoked'));
    }

    public function create()
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        return view('admin.certs.create');
    }

    public function store(StoreCertificateRequest $request)
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        $cert = Cert::create($request->all());

        return redirect()->route('admin.certs.index');
    }

    public function edit(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        return view('admin.certs.edit', compact('cert'));
    }

    public function update(UpdateCertificateRequest $request, Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        $cert->update($request->all());

        return redirect()->route('admin.certs.index');
    }

    public function show(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_show'), 403);

        return view('admin.certs.show', compact('cert'));
    }

    public function destroy(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_delete'), 403);

        $cert->delete();

        return back();
    }

    public function massDestroy(MassDestroyCertificateRequest $request)
    {
        Cert::whereIn('id', request('ids'))->delete();

        return response(null, 204);
    }
}

KeyMatcherCertificateController

app/Http/Controllers/Admin/ConverterController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Cert;

class ConverterController extends Controller
{

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Request
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $cert = Cert::where('id', $request->id)->get()->first();
        $p12Args = array(
            'friendly_name' => $cert->subjectCommonName,
            'extracerts' => storage_path('archives/','cert.ca.cer')
        );

        /** Export it to string format in order to insert it in database and to file to back it up in archives/p12/ */
        openssl_pkcs12_export($cert->publicKey, $p12String, $cert->privateKey, $request->password, $p12Args);
        openssl_pkcs12_export_to_file($cert->publicKey, storage_path('archives/p12/' . $request->id . '.p12'), $cert->privateKey, $request->password, $p12Args);

        /** Update database field 'p12' */
        Cert::where('id', $request->id)->update(['p12' => $p12String]);

        $headers = array('Content_Type: application/x-download',);
        return response()->download(storage_path('archives/p12/' . $request->id . '.p12'), $request->id . '.p12', $headers);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function Show($id)
    {
        $cert = Cert::where('id', $id)->get()->first();
        $subjectCommonName = $cert->subjectCommonName;

        if ($cert->publicKey == null OR $cert->privateKey == null){

            return redirect()->route('admin.certs.index')->with('error','Keys not found. Check if Public and Private keys exist and match.');

        } else {

            return view('admin.converter.show', compact('id', 'subjectCommonName'));
       }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        dd('Edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        dd('Update');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        dd('Destroy');
    }
}

NewSigningRequestController

app/Http/Controllers/Admin/KeyMatcherCertificateController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Params;
use App\Cert;
use File;

class KeyMatcherCertificateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $params = Params::all();
        $cert = Cert::where('id', $id)->get()->first();
        $subjectCommonName = $cert->subjectCommonName;
        $extensionsSubjectAltName = $cert->extensionsSubjectAltName;

        /** Check if csr/cert/key are in DB. */
        if($cert->certificateServerRequest != null){
          $csr_status = 'Found';
        } else {
          $csr_status = 'Not found';
        }
        if($cert->publicKey != null){
          $cert_status = 'Found';
        } else {
          $cert_status = 'Not found';
        }
        if($cert->privateKey != null){
          $key_status = 'Found';
        } else {
          $key_status = 'Not found';
        }

        /** Checks if a private key matches certificate. */
        $keyMatchesCert = openssl_x509_check_private_key($cert->publicKey, $cert->privateKey);

        if($keyMatchesCert === true){
            $keyMatchesCert = 'YES';
          } else {
            $keyMatchesCert = 'NO';
          }
          file_put_contents(storage_path('archives/tmp/') . 'temp.csr', $cert->certificateServerRequest);
          file_put_contents(storage_path('archives/tmp/') . 'temp.cer', $cert->publicKey);

          $certSHA2sum = shell_exec("openssl x509 -in archives/tmp/temp.cer -pubkey -noout -outform pem | sha256sum 2>&1");
          $csrSHA2sum = shell_exec("openssl req -in archives/tmp/temp.csr -pubkey -noout -outform pem | sha256sum 2>&1");

          if($certSHA2sum === $csrSHA2sum){
            $certMatchesCSR = 'YES';
          } else {
            $certMatchesCSR = 'NO';
          }

          File::delete(storage_path('archives/tmp/') . 'temp.csr');
          File::delete(storage_path('archives/tmp/') . 'temp.cer');  

        return view('admin.keymatcher.show', compact(
            'id',
            'params',
            'subjectCommonName',
            'extensionsSubjectAltName',
            'csr_status',
            'cert_status',
            'key_status',
            'keyMatchesCert',
            'certMatchesCSR',
            'certSHA2sum',
            'csrSHA2sum'
        ));

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

RenewCertificateController

app/Http/Controllers/Admin/RenewCertificateController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Cert;
use App\Params;
use File;
use ZipArchive;

class RenewCertificateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $cert = Cert::where('id', $request->id)->get()->first();
        $config = '/usr/lib/ssl/openssl.cnf';

        /** Clean DNS: entries in ca.cnf */
        shell_exec("sudo /opt/subjectAltNameRemoval.sh 2>&1");

        /** Open ca.cnf, insert extensionsSubjectAltName and save ca.cnf */
        $insertSAN = file_get_contents($config);
        $insertSAN = str_replace("DNS:", $cert->extensionsSubjectAltName, $insertSAN);
        file_put_contents($config, $insertSAN);
        unset($insertSAN);

        /** Arguments pass to the CSR */
        $configArgs = array(
            'config' => $config,
            'encrypt_key' => false,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
            'subjectAltName' => $cert->extensionsSubjectAltName, // Not needed since it is hardcoded (above) in config file.
            'digest_alg' => $cert->signatureTypeSN,
            'x509_extensions' => $cert->extensionsExtendedKeyUsage
          );

        $serialNumber = random_int(160000000001, 170000000001); // serial for external CSR in Decimal format.
        $serialNumberHex = dechex($serialNumber); // serial for external CSR in Hexadecimal format.
        $cacert = file_get_contents('/opt/ca/cacert.pem');
        $pkeyid = array(file_get_contents('/opt/ca/private/cakey.pem'), $request->password );

        /** Sign csr from DB */
        $csr_sign = openssl_csr_sign($cert->certificateServerRequest , $cacert, $pkeyid, $request->validityPeriod, $configArgs, $serialNumber);

        /** Export signed certificate to string variable. */
        openssl_x509_export($csr_sign, $publicKey);

        /** Replace publickey for monitoring */
        File::delete(storage_path('archives/monitor/' . $cert->id . '.cer'));
        file_put_contents(storage_path('archives/monitor/' . $cert->id . '.cer'), $publicKey);

        /** Update archive/keypairs archive with new certificate */
        $zipFile = $cert->id . '.zip';

        $zip = new ZipArchive();
        $path = storage_path('archives/keypairs/');
        $zip->open($path . $zipFile, ZipArchive::CREATE);
        //$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
        $zip->addFile(storage_path('archives/monitor/' . $cert->id . '.cer'), $cert->id . '.cer');
        $zip->close();

        shell_exec("sudo /opt/subjectAltNameRemoval.sh 2>&1");

        /** Certificate parser */
        $certParser = openssl_x509_parse($publicKey);

        /** DB updates */
        Cert::where('id', $cert->id)->update(['expiryDate' => $request->validityPeriod]);
        Cert::where('id', $cert->id)->update(['serialNumber' => $serialNumber]);
        Cert::where('id', $cert->id)->update(['serialNumberHex' => $serialNumberHex]);
        Cert::where('id', $cert->id)->update(['publicKey' => $publicKey]);
        Cert::where('id', $cert->id)->update(['p12' => null]);
        Cert::where('id', $cert->id)->update(['validFrom' => $certParser['validFrom']]);
        Cert::where('id', $cert->id)->update(['validTo' => $certParser['validTo']]);
        Cert::where('id', $cert->id)->update(['validFrom_time_t' => $certParser['validFrom_time_t']]);
        Cert::where('id', $cert->id)->update(['validTo_time_t' => $certParser['validTo_time_t']]);
        Cert::where('id', $cert->id)->update(['hash' => $certParser['hash']]);
        Cert::where('id', $cert->id)->update(['extensionsSubjectKeyIdentifier' => $certParser['extensions']['subjectKeyIdentifier']]);
        Cert::where('id', $cert->id)->update(['extensionsAuthorityKeyIdentifier' => $certParser['extensions']['authorityKeyIdentifier']]);
        Cert::where('id', $cert->id)->update(['status' => 'Valid']);

        return redirect()->route('admin.certs.index')->with('success', "Certificate successfully renewed.");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $params = Params::all();
        $cert = Cert::where('id', $id)->get()->first();
        $subjectCommonName = $cert->subjectCommonName;
        $extensionsSubjectAltName = $cert->extensionsSubjectAltName;

        if ($cert->certificateServerRequest == null OR $cert->privateKey == null OR $cert->status == 'Revoked'){

            return redirect()->route('admin.certs.index')->with('error',"Keys not found. Check if Request (CSR) and Private keys exist and match OR if certificate is Revoked.");

        } elseif ($cert->issuerCN !== 'LIQUABit Root CA') { // Extract issuer from cert ca.cert.cert nad meke it dynamic.

            return redirect()->route('admin.certs.index')->with('error', "Issuer mismatch. It seems that this certificate has been issued by: {$cert->issuerCN}");

       } else {

            return view('admin.renew.show', compact('id', 'params', 'subjectCommonName', 'extensionsSubjectAltName'));
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

RevokeCertificateController

app/Http/Controllers/Admin/RevokeCertificateController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Cert;
use App\Params;
use File;

class RevokeCertificateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $cert = Cert::where('id', $request->id)->get()->first();
        $config = '/usr/lib/ssl/openssl.cnf';
        $certFile = storage_path('archives/tmp/' . $request->id . '.cer');
        $password = $request->password;
        $crlFile = storage_path('archives/ca-g2.crl');

        file_put_contents(storage_path('archives/tmp/' . $request->id . '.cer'), $cert->publicKey);

        $revoke = shell_exec("sudo openssl ca -config $config -revoke $certFile -key $password -batch 2>&1");
        $revoked = substr($revoke, -18, 17);
        //dd($revoke, $revoked);
        if($revoked == 'Data Base Updated'){

            File::delete(storage_path('archives/tmp/' . $request->id . '.cer'));
            File::delete(storage_path('archives/keypairs/' . $request->id . '.zip'));
            File::delete(storage_path('archives/monitor/' . $request->id . '.cer'));
            File::delete(storage_path('archives/p12/' . $request->id . '.p12'));

            Cert::where('id', $request->id)->update(['status' => 'Revoked']);
            Cert::where('id', $request->id)->update(['revokedReason' => $request->revokedReason]);

            shell_exec("sudo openssl ca -gencrl -config $config -key $request->password -out $crlFile -batch 2>&1");

            return redirect()->route('admin.certs.index')->with('success','Successfully revoked.');

        } else {

            return redirect()->route('admin.certs.index')->with('error', " Trace: {$revoke}");
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $params = Params::all();
        $cert = Cert::where('id', $id)->get()->first();
        $subjectCommonName = $cert->subjectCommonName;
        $extensionsSubjectAltName = $cert->extensionsSubjectAltName;


        /** Return error if the certificate can´t be revoked. */
        if($cert->status == 'Revoked')
            {
                return redirect()->route('admin.certs.index')->with('error','Certificate is already revoked.');

            } elseif ($cert->status == 'Expired')
            {
                return redirect()->route('admin.certs.index')->with('error','Certificate is expired.');

            } elseif ($cert->publicKey == null) {

                return redirect()->route('admin.certs.index')->with('error','Certificate not found.');

            } else {

                return view('admin.revoke.show', compact('id', 'params', 'subjectCommonName', 'extensionsSubjectAltName'));
            }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

SigningRequestController

app/Http/Controllers/Admin/SigningRequestController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroySigningCertificateRequest;
use App\Http\Requests\StoreSigningCertificateRequest;
use App\Http\Requests\UpdateSigningCertificateRequest;
use App\Cert;
use App\Params;
use File;
use Carbon\Carbon;
use ZipArchive;

class SigningRequestController extends Controller
{
    public function create()
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        $params = Params::all();

        return view('admin.certs.sign-req.create', compact('params'));
    }

    public function store(StoreSigningCertificateRequest $request)
    {
        abort_unless(\Gate::allows('certificate_create'), 403);

        $subjectCommonName = openssl_csr_get_subject($request->certificateServerRequest, true);
        $cacert = file_get_contents('/opt/ca/cacert.pem');
        $pkeyid = array(file_get_contents('/opt/ca/private/cakey.pem'), $request->password );
        $serial = random_int(260001, 270001); // serial for external CSR

        // Default location for OpenSSL Config file.
        $config = '/usr/lib/ssl/openssl.cnf';

        // Clear SAN DNS entries if previous error.
        shell_exec("sudo /opt/subjectAltNameRemoval.sh 2>&1");

        // Extracting SAN fron CSR.
        $random_blurp = rand(1000,99999);
        $tempCSR = "/tmp/csr-" . $random_blurp . ".csr.pem";
        $write_csr = file_put_contents($tempCSR, $request->certificateServerRequest);
        if($write_csr !== FALSE) {
            $san = trim(shell_exec("openssl req -noout -text -in " . $tempCSR . " | grep -e 'DNS:' -e 'IP:' -e 'email:'")); // Not sure if 'email:' works.
        }
        unlink($tempCSR);

        // In case the CSR file doesn´t include SAN.
        if($san == ""){
            $san = 'DNS:' . $subjectCommonName['CN'];
            }

        // Include subjectAltName in openssl.cnf.
        $caConfFile = file_get_contents($config);

        // Do replacements for SAN in ca.cnf.
        $caConfFile = str_replace("DNS:",$san, $caConfFile);
        file_put_contents($config, $caConfFile);
        unset($caConfFile); // Clears the content of the file.

        $configArgs = array(
            'config' => $config,
            'encrypt_key' => false,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
            'digest_alg' => $request->signatureTypeSN,
            'x509_extensions' => $request->extensionsExtendedKeyUsage );

        // Sign certificate and export to string.
        $cert = openssl_csr_sign($request->certificateServerRequest , $cacert, $pkeyid, $request->validityPeriod, $configArgs, $serial);
        openssl_x509_export($cert, $publicKey);

        // Save and zip CSR and Cert in file to ZIP//
        file_put_contents(storage_path('archives/tmp/cert.csr'), $request->certificateServerRequest);
        file_put_contents(storage_path('archives/tmp/cert.cer'), $publicKey);

        // Clean SAN DNS entries.
        shell_exec("sudo /opt/subjectAltNameRemoval.sh 2>&1");

        // Parse Certificate Info.
        $cert_parse = openssl_x509_parse($publicKey);

        $request['publicKey'] = $publicKey;
        $request['name'] = $cert_parse['name'];
        $request['subject'] = $cert_parse['subject'];
        $request['subjectCommonName'] = $cert_parse['subject']['CN'];
        $request['subjectContry'] = $cert_parse['subject']['C'];
        $request['subjectState'] = $cert_parse['subject']['ST'];
        $request['subjectLocality'] = $cert_parse['subject']['L'];
        $request['subjectOrganization'] = $cert_parse['subject']['O'];
        $request['subjectOrganizationUnit'] = $cert_parse['subject']['OU'];
        $request['hash'] = $cert_parse['hash'];
        $request['issuer'] = $cert_parse['issuer'];
        $request['issuerCN'] = $cert_parse['issuer']['CN'];
        $request['issuerContry'] = $cert_parse['issuer']['C'];
        $request['issuerState'] = $cert_parse['issuer']['ST'];
            //$request['issuerLocality'] = $cert_parse['issuer']['L'];
            $request['issuerOrganization'] = $cert_parse['issuer']['O'];
            $request['issuerOrganizationUnit'] = $cert_parse['issuer']['OU'];
            $request['version'] = $cert_parse['version'];
            $request['serialNumber'] = $cert_parse['serialNumber'];
            $request['serialNumberHex'] = $cert_parse['serialNumberHex'];
            $request['validFrom'] = $cert_parse['validFrom'];
            $request['validTo'] = $cert_parse['validTo'];
            $request['validFrom_time_t'] = $cert_parse['validFrom_time_t'];
            $request['validTo_time_t'] = $cert_parse['validTo_time_t'];
            $request['signatureTypeSN'] = $cert_parse['signatureTypeSN'];
            $request['signatureTypeLN'] = $cert_parse['signatureTypeLN'];
            $request['signatureTypeNID'] = $cert_parse['signatureTypeNID'];
        //$purposes = $cert_parse['purposes']['1']['2']; dd($purposes);
        $request['purposes'] = 'Not Implemented';
        $request['extensions'] = $cert_parse['extensions'];
        $request['extensionsBasicConstraints'] = $cert_parse['extensions']['basicConstraints'];
            //$extensionsExtendedKeyUsage = $cert_parse['extensions']['nsCertType'];
            $request['extensionsKeyUsage'] = $cert_parse['extensions']['keyUsage'];
            $request['extensionsExtendedKeyUsage'] = $cert_parse['extensions']['extendedKeyUsage'];
            $request['extensionsSubjectKeyIdentifier'] = $cert_parse['extensions']['subjectKeyIdentifier'];
            $request['extensionsAuthorityKeyIdentifier'] = $cert_parse['extensions']['authorityKeyIdentifier'];
            $request['extensionsSubjectAltName'] = $cert_parse['extensions']['subjectAltName'];
            $request['extensionsCrlDistributionPoints'] = $cert_parse['extensions']['crlDistributionPoints'];

        /** Convert dates. */
        $validTo_time_t = date(DATE_RFC2822, $request['validTo_time_t']);
        $expiryDate = Carbon::parse(Carbon::now())->diffInDays($validTo_time_t);
        $request['expiryDate'] = $expiryDate;
        $cert = Cert::create($request->all(), $publicKey);
        $cert->save();

        /** Zip the .cer and .key saved in storage_path/tmp and move it to storage_path/archives. */
        $zipFile = $cert->id . '.zip';
        $zip = new ZipArchive();
        $path = storage_path('archives/keypairs/');

        $zip->open($path . $zipFile, ZipArchive::CREATE | ZipArchive::CREATE);

        //$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
        $files = File::files(storage_path('archives/tmp/'));

        foreach ($files as $name => $file)
        {
            /** Skipping all subfolders */
            if (!$file->isDir()) {
                $filePath = $file->getRealPath();

                /** extracting filename with substr/strlen */
                $relativePath = '' . substr($filePath, strlen($path) -5);
                $zip->addFile($filePath, $relativePath);
            }
        }
        $zip->close();

        /** Include certificate to local monitor  */
        file_put_contents(storage_path('archives/monitor/' . $cert->id . '.cer'), $publicKey);

        File::delete(storage_path('archives/tmp/' . 'cert.csr'));
        File::delete(storage_path('archives/tmp/' . 'cert.cer'));

        return redirect()->route('admin.certs.index');
    }

    public function edit(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        return view('admin.certs.edit', compact('cert'));
    }

    public function update(UpdateSigningCertificateRequest $request, Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_edit'), 403);

        $cert->update($request->all());

        return redirect()->route('admin.certs.index');
    }

    public function show(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_show'), 403);

        return view('admin.certs.show', compact('cert'));
    }

    public function destroy(Cert $cert)
    {
        abort_unless(\Gate::allows('certificate_delete'), 403);

        $cert->delete();

        return back();
    }

    public function massDestroy(MassDestroySigningCertificateRequest $request)
    {
        Cert::whereIn('id', request('ids'))->delete();

        return response(null, 204);
    }
}

UpdateCRLController

app/Http/Controllers/Admin/UpdateCRLController.php
<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class UpdateCRLController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
      abort_unless(\Gate::allows('certificate_access'), 403);

      return view('admin.update-crl.index');

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      $password = $request->password;
      $crlPath = storage_path('archives/ca-g2.crl');
      $updateCRL = shell_exec("sudo openssl ca -config /usr/lib/ssl/openssl.cnf -gencrl -out $crlPath -key $request->password -batch 2>&1");

      return redirect()->route('admin.certs.index');

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
      //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
Back to top