Create a CSR for a CiviConnect application.

@param array $keyPair
Array with elements:
- privatekey: string.
- publickey: string.
@param string $dn
Distinguished name.
@return string
CSR data.
167655
public static function createAppCSR($keyPair, $dn) {
    $privKey = new \Crypt_RSA();
    $privKey->loadKey($keyPair['privatekey']);

    $pubKey = new \Crypt_RSA();
    $pubKey->loadKey($keyPair['publickey']);
    $pubKey->setPublicKey();

    $x509 = new \File_X509();
    $x509->setPrivateKey($privKey);
    $x509->setDN($dn);

    $x509->loadCSR($x509->saveCSR($x509->signCSR(Constants::CERT_SIGNATURE_ALGORITHM)));
    $x509->setExtension('id-ce-keyUsage', array('keyEncipherment'));

    $csrData = $x509->signCSR(Constants::CERT_SIGNATURE_ALGORITHM);
    return $x509->saveCSR($csrData);
  }
161307
function signCSR($signatureAlgorithm = 'sha1WithRSAEncryption')
    {
        if (!is_object($this->privateKey) || empty($this->dn)) {
            return false;
        }

        $origPublicKey = $this->publicKey;
        $class = get_class($this->privateKey);
        $this->publicKey = new $class();
        $this->publicKey->loadKey($this->privateKey->getPublicKey());
        $this->publicKey->setPublicKey();
        if (!($publicKey = $this->_formatSubjectPublicKey())) {
            return false;
        }
        $this->publicKey = $origPublicKey;

        $currentCert = isset($this->currentCert) ? $this->currentCert : NULL;
        $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: NULL;

        if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['certificationRequestInfo'])) {
            $this->currentCert['signatureAlgorithm']['algorithm'] =
                $signatureAlgorithm;
            if (!empty($this->dn)) {
                $this->currentCert['certificationRequestInfo']['subject'] = $this->dn;
            }
            $this->currentCert['certificationRequestInfo']['subjectPKInfo'] = $publicKey;
        } else {
            $this->currentCert = array(
                'certificationRequestInfo' =>
                    array(
                        'version' => 'v1',
                        'subject' => $this->dn,
                        'subjectPKInfo' => $publicKey
                    ),
                'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm),
                'signature'          => false // this is going to be overwritten later
            );
        }

        // resync $this->signatureSubject
        // save $certificationRequestInfo in case there are any File_ASN1_Element objects in it
        $certificationRequestInfo = $this->currentCert['certificationRequestInfo'];
        $this->loadCSR($this->saveCSR($this->currentCert));

        $result = $this->_sign($this->privateKey, $signatureAlgorithm);
        $result['certificationRequestInfo'] = $certificationRequestInfo;

        $this->currentCert = $currentCert;
        $this->signatureSubject = $signatureSubject;

        return $result;
    }
1164236
public function DKIM_Sign($signHeader)
    {
        if (!defined('PKCS7_TEXT')) {
            if ($this->exceptions) {
                throw new Exception($this->lang('extension_missing') . 'openssl');
            }

            return '';
        }
        $privKeyStr = !empty($this->DKIM_private_string) ?
            $this->DKIM_private_string :
            file_get_contents($this->DKIM_private);
        if ('' != $this->DKIM_passphrase) {
            $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
        } else {
            $privKey = openssl_pkey_get_private($privKeyStr);
        }
        if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
            openssl_pkey_free($privKey);

            return base64_encode($signature);
        }
        openssl_pkey_free($privKey);

        return '';
    }
1275027
static private function parseDsn($dsnStr) {
        if( empty($dsnStr) ){return false;}
        $info = parse_url($dsnStr);
        if(!$info) {
            return false;
        }
        $dsn = array(
            'type'      =>  $info['scheme'],
            'username'  =>  isset($info['user']) ? $info['user'] : '',
            'password'  =>  isset($info['pass']) ? $info['pass'] : '',
            'hostname'  =>  isset($info['host']) ? $info['host'] : '',
            'hostport'  =>  isset($info['port']) ? $info['port'] : '',
            'database'  =>  isset($info['path']) ? substr($info['path'],1) : '',
            'charset'   =>  isset($info['fragment'])?$info['fragment']:'utf8',
        );
        
        if(isset($info['query'])) {
            parse_str($info['query'],$dsn['params']);
        }else{
            $dsn['params']  =   array();
        }
        return $dsn;
     }
837203
protected function conn_create($dsn)
    {
        // Get database specific connection options
        $dsn_options = $this->dsn_options($dsn);

        $function = $this->db_pconn ? 'oci_pconnect' : 'oci_connect';

        if (!function_exists($function)) {
            $this->db_error     = true;
            $this->db_error_msg = 'OCI8 extension not loaded. See http://php.net/manual/en/book.oci8.php';

            rcube::raise_error(array('code' => 500, 'type' => 'db',
                'line' => __LINE__, 'file' => __FILE__,
                'message' => $this->db_error_msg), true, false);

            return;
        }

        // connect
        $dbh = @$function($dsn['username'], $dsn['password'], $dsn_options['database'], $dsn_options['charset']);

        if (!$dbh) {
            $error              = oci_error();
            $this->db_error     = true;
            $this->db_error_msg = $error['message'];

            rcube::raise_error(array('code' => 500, 'type' => 'db',
                'line' => __LINE__, 'file' => __FILE__,
                'message' => $this->db_error_msg), true, false);

            return;
        }

        // configure session
        $this->conn_configure($dsn, $dbh);

        return $dbh;
    }
1314625
public String generateCertificationRequest(String subject, KeyPair pair)
            throws InvalidArgumentException {

        try {
            PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
                    new X500Principal("CN=" + subject), pair.getPublic());

            JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withECDSA");

            if (null != SECURITY_PROVIDER) {
                csBuilder.setProvider(SECURITY_PROVIDER);
            }
            ContentSigner signer = csBuilder.build(pair.getPrivate());

            return certificationRequestToPEM(p10Builder.build(signer));
        } catch (Exception e) {

            logger.error(e);
            throw new InvalidArgumentException(e);

        }

    }
122331
public function pemEncode($keypair)
    {
        if (is_array($keypair) && (strlen($keypair[0]) < 64 || strlen($keypair[1]) < 128)) {
            throw new \Exception('Invalid or corrupt secp256k1 keypair provided. Cannot decode the supplied PEM data.');
        }

        $dec         = '';
        $byte        = '';
        $beg_ec_text = '';
        $end_ec_text = '';
        $ecpemstruct = array();
        $digits      = array();

        for ($x = 0; $x < 256; $x++) {
            $digits[$x] = chr($x);
        }

        $ecpemstruct = array(
                'sequence_beg' => '30',
                'total_len'    => '74',
                'int_sec_beg'  => '02',
                'int_sec_len'  => '01',
                'int_sec_val'  => '01',
                'oct_sec_beg'  => '04',
                'oct_sec_len'  => '20',
                'oct_sec_val'  => $keypair[0],
                'a0_ele_beg'   => 'a0',
                'a0_ele_len'   => '07',
                'obj_id_beg'   => '06',
                'obj_id_len'   => '05',
                'obj_id_val'   => '2b8104000a',
                'a1_ele_beg'   => 'a1',
                'a1_ele_len'   => '44',
                'bit_str_beg'  => '03',
                'bit_str_len'  => '42',
                'bit_str_val'  => '00'.$keypair[1],
        );

        $beg_ec_text = '-----BEGIN EC PRIVATE KEY-----';
        $end_ec_text = '-----END EC PRIVATE KEY-----';

        $dec = trim(implode($ecpemstruct));

        if (strlen($dec) < 230) {
            throw new \Exception('Invalid or corrupt secp256k1 keypair provided. Cannot encode the supplied data.');
        }

        $dec = Util::decodeHex('0x'.$dec);

        while (Math::cmp($dec, '0') > 0) {
            $dv = Math::div($dec, '256');
            $rem = Math::mod($dec, '256');
            $dec = $dv;
            $byte = $byte.$digits[$rem];
        }

        $byte = $beg_ec_text."\r\n".chunk_split(base64_encode(strrev($byte)), 64).$end_ec_text;

        $this->pemEncoded = $byte;

        return $byte;
    }
146169
public function createConnection($dsn, array $config, array $options)
    {
        $username = array_get($config, 'username');

        $password = array_get($config, 'password');

        return new PDO($dsn, $username, $password, $options);
    }
917667
public static function cryptoKeyName($project, $location, $keyRing, $cryptoKey)
    {
        return self::getCryptoKeyNameTemplate()->render([
            'project' => $project,
            'location' => $location,
            'key_ring' => $keyRing,
            'crypto_key' => $cryptoKey,
        ]);
    }
1211204
public function tokenCreate($cid, $description = null, $customset = null)
  {
    return $this->privilegeKeyCreate($cid, $description, $customset);
  }
9454
public static function fromPrivateKey(EccPrivateKey $privateKey, AbstractNetwork $network = null): string
    {
        $digest = Hash::ripemd160($privateKey->getPublicKey()->getBuffer());

        return (new PayToPubKeyHashAddress($digest))->getAddress($network);
    }
608526
public static function createFromDsn($dsn, $username, $password)
    {
        try {
            $pdo = new \PDO($dsn, $username, $password);

            return new self($pdo);
        } catch (\Exception $exception) {
            return;
        }
    }
413017
public static function importSignatureKeyPair(HiddenString $keyData): SignatureKeyPair
    {
        return new SignatureKeyPair(
            new SignatureSecretKey(
                new HiddenString(
                    self::getKeyDataFromString(
                        Hex::decode($keyData->getString())
                    )
                )
            )
        );
    }
561422
private function getKeyPair()
    {
        $config = $this->app->make('config/database');

        // Seee if we already have a kypair
        $keyPair = $config->get('api.keypair');

        if (!$keyPair) {
            $rsa = $this->app->make(RSA::class);

            // Generate a new RSA key
            $keyPair = $rsa->createKey(2048);

            foreach ($keyPair as &$item) {
                $item = str_replace("\r\n", "\n", $item);
            }

            // Save the keypair
            $config->save('api.keypair', $keyPair);
        }

        return $keyPair;
    }
1336068
protected function afterGenerateKeyPair(KeyPairInterface $keyPair)
    {
        if ($keyPair instanceof SecureKeyPairInterface) {
            $masterKeyPairProvider = $this->getMasterKeyPairProvider();
            $masterKeyName = $this->getMasterKeyName();
            if ($masterKeyPairProvider === null) {
                throw new InaccessibleKeyPairException('Provider has an invalid master key provider specified for its secure keys');
            }
            if (!$masterKeyPairProvider->has($masterKeyName)) {
                $masterKey = $masterKeyPairProvider->generate($masterKeyName);
            } else {
                $masterKey = $masterKeyPairProvider->get($masterKeyName);
            }
            $keyPair->lock($masterKey);
        }
        return $keyPair;
    }
492701
def keypair_delete(name, profile=None, **kwargs):
    '''
    
    '''
    conn = _auth(profile, **kwargs)
    return conn.keypair_delete(name)
123940
public static function generateToken($userName, $keyString) {
        $userNameCast = (string) $userName;
        $keyStringCast = (string) $keyString;
        $multiOtpObj = new MultiotpWrapper($keyStringCast);
        return $multiOtpObj->GenerateSmsToken($userNameCast);
    }