PGP keys/certs export.

@param string   Key ID
@param resource Optional output stream
@param bool     Include private key

@return mixed Key content or enigma_error
172225
function export_key($key, $fp = null, $include_private = false)
    {
        $this->load_pgp_driver();
        $result = $this->pgp_driver->export($key, $include_private, $this->get_passwords());

        if ($result instanceof enigma_error) {
            self::raise_error($result, __LINE__);
            return $result;
        }

        if ($fp) {
            fwrite($fp, $result);
        }
        else {
            return $result;
        }
    }
647432
private function extractAuthKeyFromPemContent()
    {
        $details = openssl_pkey_get_details(openssl_pkey_get_private($this->pem));
        if (!array_key_exists('key', $details)) {
            return null;
        }

        // Remove BEGIN RSA PRIVATE KEY / END RSA PRIVATE KEY lines
        $KeyStr = trim($details['key']);
        // Support line break on *nix systems, OS, older OS, and Microsoft
        $keyArr = preg_split('/\r\n|\r|\n/', $KeyStr);
        if (strpos($KeyStr, 'BEGIN') !== false) {
            array_shift($keyArr);
            array_pop($keyArr);
        }
        $authKey = implode('', $keyArr);

        // Check auth key is not empty
        if (empty($authKey)) {
            throw new RequestException('Could not retrieve Auth key from PEM content.', 401);
        }

        return $authKey;
    }
438657
public static function encryptRsaPrivate(string $data, string $privateKey, string $format = null): string
    {
        $key = \openssl_pkey_get_private($privateKey);

        $encrypted = '';
        if (!\openssl_private_encrypt($data, $encrypted, $key, OPENSSL_PKCS1_OAEP_PADDING)) {
            throw new CryptoException('RSA private encrypt error: ' . openssl_error_string());
        }
        \openssl_pkey_free($key);

        return self::fromRaw($encrypted, $format);
    }
873745
private static void savePrivateKeyPKCS8(OutputStream os, PrivateKey key)
    throws IllegalArgumentException, IOException {

    CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, null);

  }
683373
public void setSignInfo(PrivateKey privKey, Certificate[] certChain, CRL[] crlList) {
        try {
            pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, provider, PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
            pkcs.setExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
            if (PdfName.ADBE_X509_RSA_SHA1.equals(get(PdfName.SUBFILTER))) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                for (int k = 0; k < certChain.length; ++k) {
                    bout.write(certChain[k].getEncoded());
                }
                bout.close();
                setCert(bout.toByteArray());
                setContents(pkcs.getEncodedPKCS1());
            }
            else
                setContents(pkcs.getEncodedPKCS7());
            name = PdfPKCS7.getSubjectFields(pkcs.getSigningCertificate()).getField("CN");
            if (name != null)
                put(PdfName.NAME, new PdfString(name, PdfObject.TEXT_UNICODE));
            pkcs = new PdfPKCS7(privKey, certChain, crlList, hashAlgorithm, provider, PdfName.ADBE_PKCS7_SHA1.equals(get(PdfName.SUBFILTER)));
            pkcs.setExternalDigest(externalDigest, externalRSAdata, digestEncryptionAlgorithm);
        }
        catch (Exception e) {
            throw new ExceptionConverter(e);
        }
    }
1089010
public function clientSideCert($cert, $key, $passphrase = null, $encoding = 'PEM')
    {
        $this->client_cert          = $cert;
        $this->client_key           = $key;
        $this->client_passphrase    = $passphrase;
        $this->client_encoding      = $encoding;

        return $this;
    }
669039
private function addIncludekeyToRelationsIfNotSet($includeKey, $relationships)
    {
        if (!array_key_exists($includeKey, $relationships)) {
            $relationships[$includeKey] = [];
            return $relationships;
        }

        return $relationships;
    }
1165067
def _encrypt_private(self, ret, dictkey, target):
        '''
        
        '''
        # encrypt with a specific AES key
        pubfn = os.path.join(self.opts['pki_dir'],
                             'minions',
                             target)
        key = salt.crypt.Crypticle.generate_key_string()
        pcrypt = salt.crypt.Crypticle(
            self.opts,
            key)
        try:
            pub = salt.crypt.get_rsa_pub_key(pubfn)
        except (ValueError, IndexError, TypeError):
            return self.crypticle.dumps({})
        except IOError:
            log.error('AES key not found')
            return {'error': 'AES key not found'}

        pret = {}
        if not six.PY2:
            key = salt.utils.stringutils.to_bytes(key)
        if HAS_M2:
            pret['key'] = pub.public_encrypt(key, RSA.pkcs1_oaep_padding)
        else:
            cipher = PKCS1_OAEP.new(pub)
            pret['key'] = cipher.encrypt(key)
        pret[dictkey] = pcrypt.dumps(
            ret if ret is not False else {}
        )
        return pret
1211352
protected function autoWireInclude($includeKey, $includeDefinition, $item)
    {
        // Get the included data
        $data = null;
        if (\is_array($item) || $item instanceof \ArrayAccess) {
            $data = $item[$includeKey] ?? null;
        } elseif (\is_object($item)) {
            $data = $item->$includeKey ?? null;
        } else {
            throw new IncludeException("Cannot auto-wire include for $includeKey: Cannot get include data");
        }

        if (!empty($includeDefinition['resource_type']) && $includeDefinition['resource_type'] === 'collection') {
            return new Collection($data);
        }

        // Assume unless declared, that the resource is an item.
        return new Item($data);
    }
1274938
private function pgp_encrypt(&$msg_body, $keys, $sign_key = null, $sign_pass = null)
    {
        // @TODO: Handle big bodies using (temp) files
        $result = $this->pgp_driver->encrypt($msg_body, $keys, $sign_key, $sign_pass);

        if ($result instanceof enigma_error) {
            if ($result->getCode() != enigma_error::KEYNOTFOUND) {
                self::raise_error($result, __LINE__);
            }

            return $result;
        }

        $msg_body = $result;

        return true;
    }
676077
@CheckForNull
    public static PrivateKey loadPrivateKey(final String keypem) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {
        try (StringReader certReader = new StringReader(keypem);
             BufferedReader reader = new BufferedReader(certReader)) {
            return loadPrivateKey(reader);
        }
    }
842159
function loadKey($key, $type = false)
    {
        if ($key instanceof RSA) {
            $this->privateKeyFormat = $key->privateKeyFormat;
            $this->publicKeyFormat = $key->publicKeyFormat;
            $this->k = $key->k;
            $this->hLen = $key->hLen;
            $this->sLen = $key->sLen;
            $this->mgfHLen = $key->mgfHLen;
            $this->encryptionMode = $key->encryptionMode;
            $this->signatureMode = $key->signatureMode;
            $this->password = $key->password;
            $this->configFile = $key->configFile;
            $this->comment = $key->comment;

            if (is_object($key->hash)) {
                $this->hash = new Hash($key->hash->getHash());
            }
            if (is_object($key->mgfHash)) {
                $this->mgfHash = new Hash($key->mgfHash->getHash());
            }

            if (is_object($key->modulus)) {
                $this->modulus = $key->modulus->copy();
            }
            if (is_object($key->exponent)) {
                $this->exponent = $key->exponent->copy();
            }
            if (is_object($key->publicExponent)) {
                $this->publicExponent = $key->publicExponent->copy();
            }

            $this->primes = array();
            $this->exponents = array();
            $this->coefficients = array();

            foreach ($this->primes as $prime) {
                $this->primes[] = $prime->copy();
            }
            foreach ($this->exponents as $exponent) {
                $this->exponents[] = $exponent->copy();
            }
            foreach ($this->coefficients as $coefficient) {
                $this->coefficients[] = $coefficient->copy();
            }

            return true;
        }

        if ($type === false) {
            $types = array(
                self::PUBLIC_FORMAT_RAW,
                self::PRIVATE_FORMAT_PKCS1,
                self::PRIVATE_FORMAT_XML,
                self::PRIVATE_FORMAT_PUTTY,
                self::PUBLIC_FORMAT_OPENSSH
            );
            foreach ($types as $type) {
                $components = $this->_parseKey($key, $type);
                if ($components !== false) {
                    break;
                }
            }
        } else {
            $components = $this->_parseKey($key, $type);
        }

        if ($components === false) {
            $this->comment = null;
            $this->modulus = null;
            $this->k = null;
            $this->exponent = null;
            $this->primes = null;
            $this->exponents = null;
            $this->coefficients = null;
            $this->publicExponent = null;

            return false;
        }

        if (isset($components['comment']) && $components['comment'] !== false) {
            $this->comment = $components['comment'];
        }
        $this->modulus = $components['modulus'];
        $this->k = strlen($this->modulus->toBytes());
        $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent'];
        if (isset($components['primes'])) {
            $this->primes = $components['primes'];
            $this->exponents = $components['exponents'];
            $this->coefficients = $components['coefficients'];
            $this->publicExponent = $components['publicExponent'];
        } else {
            $this->primes = array();
            $this->exponents = array();
            $this->coefficients = array();
            $this->publicExponent = false;
        }

        switch ($type) {
            case self::PUBLIC_FORMAT_OPENSSH:
            case self::PUBLIC_FORMAT_RAW:
                $this->setPublicKey();
                break;
            case self::PRIVATE_FORMAT_PKCS1:
                switch (true) {
                    case strpos($key, '-BEGIN PUBLIC KEY-') !== false:
                    case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false:
                        $this->setPublicKey();
                }
        }

        return true;
    }
963304
public static function decryptRsaPrivate(string $data, string $privateKey, string $format = null): string
    {
        $data = self::toRaw($data, $format);
        $key = \openssl_pkey_get_private($privateKey);

        $decrypted = '';
        if (!\openssl_private_decrypt($data, $decrypted, $key, OPENSSL_PKCS1_OAEP_PADDING)) {
            throw new CryptoException('RSA private decrypt error: ' . openssl_error_string());
        }
        \openssl_pkey_free($key);

        return $decrypted;
    }
475358
private static void savePrivateKeyPKCS1(OutputStream os, PrivateKey key)
    throws IllegalArgumentException, IOException {

    CertificateUtils.savePrivateKey(os, key, Encoding.PEM, null, new char[0],
      true);

  }
1071027
function exportKs (password, privateKey, salt, iv, type, option = {}) {
  if (!password || !privateKey || !type) {
    throw new Error('Missing parameter! Make sure password, privateKey and type provided')
  }

  if (!crypto.isPrivateKey(privateKey)) {
    throw new Error('given Private Key is not a valid Private Key string');
  }

  salt = salt || util.bytesToHexUpperString(crypto.generateSalt());
  iv = iv || util.bytesToHexUpperString(crypto.generateIv())

  return crypto.marshal(
    crypto.deriveKey(password, salt, option), privateKey,
    util.strToBuffer(salt), util.strToBuffer(iv), type, option
  );
}
1158162
private static function ensureKeyPair()
    {
        $publicKeyLocation = DIR_DATA . 'xentriq/security/xentriq.security.website.pub';
        $privateKeyLocation = DIR_DATA . 'xentriq/security/xentriq.security.website.priv';
        
        if (!file_exists($publicKeyLocation) || !file_exists($privateKeyLocation)) {
            $privateKey = openssl_pkey_new(array(
                'private_key_bits' => 2048
            ));
            
            File::setContent($privateKeyLocation, '', true);
            if (!openssl_pkey_export_to_file($privateKey, $privateKeyLocation)) {
                throw new SecurityException('Unable to generate security token');
            }
            
            $privateKeyDetails = openssl_pkey_get_details($privateKey);
            File::setContent($publicKeyLocation, $privateKeyDetails['key'], true);
        }
    }
782109
public function loadPrivateKey(PrivateKeyConfiguration $key) : PrivateKey
    {
        if ($key->isFile()) {
            $privateKey = File::getFileContents($key->getFilePath());
        } else {
            $privateKey = $key->getContents();
        }

        return PrivateKey::create($privateKey, $key->getPassPhrase());
    }