Save a SPKAC CSR request

@param array $csr
@param int $format optional
@access public
@return string
170630
function saveSPKAC($spkac, $format = self::FORMAT_PEM)
    {
        if (!is_array($spkac) || !isset($spkac['publicKeyAndChallenge'])) {
            return false;
        }

        $algorithm = $this->_subArray($spkac, 'publicKeyAndChallenge/spki/algorithm/algorithm');
        switch (true) {
            case !$algorithm:
            case is_object($spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']):
                break;
            default:
                switch ($algorithm) {
                    case 'rsaEncryption':
                        $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']
                            = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey'])));
                }
        }

        $asn1 = new ASN1();

        $asn1->loadOIDs($this->oids);
        $spkac = $asn1->encodeDER($spkac, $this->SignedPublicKeyAndChallenge);

        switch ($format) {
            case self::FORMAT_DER:
                return $spkac;
            // case self::FORMAT_PEM:
            default:
                // OpenSSL's implementation of SPKAC requires the SPKAC be preceded by SPKAC= and since there are pretty much
                // no other SPKAC decoders phpseclib will use that same format
                return 'SPKAC=' . base64_encode($spkac);
        }
    }
95108
public function export($format)
    {
        $exporter = $this->container->get('claroline.exporter.' . $format);
        $exporterManager = $this->container->get('claroline.manager.exporter_manager');
        $file = $exporterManager->export('Claroline\CoreBundle\Entity\User', $exporter);
        $response = new StreamedResponse();

        $response->setCallBack(
            function () use ($file) {
                readfile($file);
            }
        );

        $response->headers->set('Content-Transfer-Encoding', 'octet-stream');
        $response->headers->set('Content-Type', 'application/force-download');
        $response->headers->set('Content-Disposition', 'attachment; filename=users.' . $format);

        switch ($format) {
            case 'csv': $response->headers->set('Content-Type', 'text/csv'); break;
            case 'xls': $response->headers->set('Content-Type', 'application/vnd.ms-excel'); break;
        }

        $response->headers->set('Connection', 'close');

        return $response;
    }
756018
public function format($format)
    {
        $pad    = false;
        $rChar  = 'hmsfHMS';
        $string = $this->format = $format;
        $string = static::encode($string, $rChar);

        // Perform rounding.
        $this->round = static::maxRound($format);

        // Decimal years, weeks, days, hours, minutes, and seconds
        static::fmtRep('Y', $string, $this->years);
        static::fmtRep('W', $string, $this->weeks);
        static::fmtRep('D', $string, $this->days);
        static::fmtRep('H', $string, $this->hours);
        static::fmtRep('M', $string, $this->min);
        static::fmtRep('S', $string, $this->sec);

        // Leading zeros h m s
        $string = str_replace('0h', sprintf('%02d', $this->h), $string);
        $string = str_replace('0m', sprintf('%02d', $this->m), $string);
        $string = str_replace('0s', sprintf('%02d', $this->s), $string);

        // No leading zeros, h m s
        $string = str_replace('h', $this->h, $string);
        $string = str_replace('m', $this->m, $string);
        $string = str_replace('s', $this->s, $string);

        // Fractional seconds.
        if (preg_match_all('/([0-9])f/', $string, $m)) {
            for ($i = 0; $i < count($m[0]); $i++) {
                $f = substr($this->f, 0, $m[1][$i]);

                if ($pad) {
                    $f      = str_pad($f, $m[1][$i], '0');
                    $string = str_replace($m[0][$i], $f, $string);
                } else {
                    if ($f == 0) {
                        $string = str_replace('.' . $m[0][$i], '', $string);
                        $string = str_replace($m[0][$i], '', $string);
                    } else {
                        $string = str_replace($m[0][$i], $f, $string);
                    }
                }
            }
        }

        return static::decode($string, $rChar);
    }
281703
private function createCsvResponse($fileName, $header, $records) {
    $csv = Writer::createFromString('');

    $csv->insertOne($header);
    $csv->insertAll($records);

    $response = new Response();
    $response->setContent($csv);

    $response->headers->set('Content-Type', 'text/csv');
    $response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '"');

    return $response;
  }
261646
public function write( $value, $format = FALSE )
	{
		if( $format )
		{
			if( version_compare( phpversion(), '5.4.0' ) >= 0 )
				$json	= json_encode( $value, JSON_PRETTY_PRINT );
			else
				$json	= ADT_JSON_Formater::format( json_encode( $value ) );
		}
		else
			$json	= json_encode( $value );
		return FS_File_Writer::save( $this->filePath, $json );
	}
1162971
function saveSPKAC($spkac, $format = FILE_X509_FORMAT_PEM)
    {
        if (!is_array($spkac) || !isset($spkac['publicKeyAndChallenge'])) {
            return false;
        }

        $algorithm = $this->_subArray($spkac, 'publicKeyAndChallenge/spki/algorithm/algorithm');
        switch (true) {
            case !$algorithm:
            case is_object($spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']):
                break;
            default:
                switch ($algorithm) {
                    case 'rsaEncryption':
                        $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']
                            = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey'])));
                }
        }

        $asn1 = new File_ASN1();

        $asn1->loadOIDs($this->oids);
        $spkac = $asn1->encodeDER($spkac, $this->SignedPublicKeyAndChallenge);

        switch ($format) {
            case FILE_X509_FORMAT_DER:
                return $spkac;
            // case FILE_X509_FORMAT_PEM:
            default:
                // OpenSSL's implementation of SPKAC requires the SPKAC be preceded by SPKAC= and since there are pretty much
                // no other SPKAC decoders phpseclib will use that same format
                return 'SPKAC=' . base64_encode($spkac);
        }
    }
247095
protected function renderSalts($format)
    {
        foreach ($this->saltsVariables as $name) {
            if ($this->getOption('format') === 'yaml') {
                $name = strtolower($name);
            }

            $this->line(sprintf($format, $name, base64_encode(Str::randomBytes(48))));
        }
    }
95458
public static function saveCssFile(\core_kernel_classes_resource $item, $lang, $styleSheetPath, $cssArr)
    {
        $directory = \taoItems_models_classes_ItemsService::singleton()->getItemDirectory($item, $lang);

        $file = $directory->getFile($styleSheetPath);

        // make sure that 'no custom css' means exactly that
        if (empty($cssArr) && $file->exists()) {
            $file->delete();
        }

        $css = self::_buildWarning() . self::arrayToCss($cssArr);
        return $file->put($css);
    }
112429
public function getHeaders($filename, $format = self::FORMAT_GUZZLE) {

        $rawHeaders = $this->getFile($filename);

        preg_match_all('/(.+):\ (.+)/i', $rawHeaders, $matches);

        // Curl format
        if($format == self::FORMAT_CURL) return $matches[0];

        // Guzzle format
        $headers = array();

        foreach($matches[0] as $i => $matche) {
            $headers[$matches[1][$i]] = $matches[2][$i];
        }

        return $headers;
    }
336976
protected function createCsrWithSANsObject(CertificateRequest $certificateRequest)
    {
        $sslConfigTemplate = <<<'EOL'
[ req ]
distinguished_name = req_distinguished_name
req_extensions = v3_req
[ req_distinguished_name ]
[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @req_subject_alt_name
[ req_subject_alt_name ]
%s
EOL;
        $sslConfigDomains = [];

        $distinguishedName = $certificateRequest->getDistinguishedName();
        $domains = array_merge(
            [$distinguishedName->getCommonName()],
            $distinguishedName->getSubjectAlternativeNames()
        );

        foreach (array_values($domains) as $index => $domain) {
            $sslConfigDomains[] = 'DNS.'.($index + 1).' = '.$domain;
        }

        $sslConfigContent = sprintf($sslConfigTemplate, implode("\n", $sslConfigDomains));
        $sslConfigFile = tempnam(sys_get_temp_dir(), 'acmephp_');

        try {
            file_put_contents($sslConfigFile, $sslConfigContent);

            $resource = $certificateRequest->getKeyPair()->getPrivateKey()->getResource();

            $csr = openssl_csr_new(
                $this->getCSRPayload($distinguishedName),
                $resource,
                [
                    'digest_alg' => 'sha256',
                    'config' => $sslConfigFile,
                ]
            );

            openssl_free_key($resource);

            if (!$csr) {
                throw new CSRSigningException(
                    sprintf('OpenSSL CSR signing failed with error: %s', openssl_error_string())
                );
            }

            return $csr;
        } finally {
            unlink($sslConfigFile);
        }
    }
735221
public function makeExportableUrl($format)
    {
        $payload = array_merge([
            'module' => $this->url(),
            'format' => $format,
        ], Request::all());

        return route('scaffold.export', $payload);
    }
195095
public function getDataRemessa($format){
        if(is_null($this->dataRemessa)){
            return Carbon::now()->format($format);
        }
        return $this->dataRemessa->format($format);
    }
83533
public static function string($value, $format = null)
    {
        if (is_null($format)) {
            $format = '%s';
        }

        return sprintf($format, $value);
    }
34375
function loadCSR($csr, $mode = self::FORMAT_AUTO_DETECT)
    {
        if (is_array($csr) && isset($csr['certificationRequestInfo'])) {
            unset($this->currentCert);
            unset($this->currentKeyIdentifier);
            unset($this->signatureSubject);
            $this->dn = $csr['certificationRequestInfo']['subject'];
            if (!isset($this->dn)) {
                return false;
            }

            $this->currentCert = $csr;
            return $csr;
        }

        // see http://tools.ietf.org/html/rfc2986

        $asn1 = new ASN1();

        if ($mode != self::FORMAT_DER) {
            $newcsr = $this->_extractBER($csr);
            if ($mode == self::FORMAT_PEM && $csr == $newcsr) {
                return false;
            }
            $csr = $newcsr;
        }
        $orig = $csr;

        if ($csr === false) {
            $this->currentCert = false;
            return false;
        }

        $asn1->loadOIDs($this->oids);
        $decoded = $asn1->decodeBER($csr);

        if (empty($decoded)) {
            $this->currentCert = false;
            return false;
        }

        $csr = $asn1->asn1map($decoded[0], $this->CertificationRequest);
        if (!isset($csr) || $csr === false) {
            $this->currentCert = false;
            return false;
        }

        $this->_mapInAttributes($csr, 'certificationRequestInfo/attributes', $asn1);
        $this->_mapInDNs($csr, 'certificationRequestInfo/subject/rdnSequence', $asn1);

        $this->dn = $csr['certificationRequestInfo']['subject'];

        $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']);

        $algorithm = &$csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm'];
        $key = &$csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'];
        $key = $this->_reformatKey($algorithm, $key);

        switch ($algorithm) {
            case 'rsaEncryption':
                $this->publicKey = new RSA();
                $this->publicKey->loadKey($key);
                $this->publicKey->setPublicKey();
                break;
            default:
                $this->publicKey = null;
        }

        $this->currentKeyIdentifier = null;
        $this->currentCert = $csr;

        return $csr;
    }
1268979
function getSubjectDN($format = FILE_X509_DN_ARRAY)
    {
        switch (true) {
            case !empty($this->dn):
                return $this->getDN($format);
            case !isset($this->currentCert) || !is_array($this->currentCert):
                break;
            case isset($this->currentCert['tbsCertificate']):
                return $this->getDN($format, $this->currentCert['tbsCertificate']['subject']);
            case isset($this->currentCert['certificationRequestInfo']):
                return $this->getDN($format, $this->currentCert['certificationRequestInfo']['subject']);
        }

        return false;
    }
21509
public function stylesheets(string $collection, ?string $format = null) : string {
        return $this->serve($collection, 'stylesheets', $format);
    }
1210862
public function sign(string $message, $format = self::FORMAT_PEM) {
        $inputFileName = new TempFile('smime_unsigned_');
        $inputFileName->setContent($message);

        $chainFile = new TempFile('smime_chain_');
        $chainFile->setContent($this->getChain());

        $outputFileName = new TempFile('smime_signed_');

        openssl_pkcs7_sign(
            $inputFileName,
            $outputFileName,
            $this->getCertificate(),
            $this->getPrivateKey(),
            $this->getHeaders(),
            $this->getFlags() /*, $chainFile */
        );
        $signature = $outputFileName->getContent();

        if($format != self::FORMAT_SMIME) {
            $signature = $this->extractSignature($signature);
        }

        if($format == self::FORMAT_DER) {
            $signature = base64_decode($signature);
        }

        return $signature;
    }