Generate a public/private key pair and add it to the RSAWalletService

@param boolean $usedForPasswords If the private key should be used for passwords
@return void
@see neos.flow:security:importprivatekey
438577
public function generateKeyPairCommand(bool $usedForPasswords = false)
    {
        $fingerprint = $this->rsaWalletService->generateNewKeypair($usedForPasswords);

        $this->outputLine('The key pair has been successfully generated. Use the following fingerprint to refer to it in the RSAWalletService: ' . PHP_EOL . PHP_EOL . $fingerprint . PHP_EOL);
    }
463832
protected void initPasswordDigest() {
    if(saltGenerator == null) {
      saltGenerator = new Default16ByteSaltGenerator();
    }
    if (passwordEncryptor == null) {
      passwordEncryptor = new Sha512HashDigest();
    }
    if(customPasswordChecker == null) {
      customPasswordChecker = Collections.emptyList();
    }
    if(passwordManager == null) {
      passwordManager = new PasswordManager(passwordEncryptor, customPasswordChecker);
    }
  }
240434
public function changePasswordAction()
    {
        if ($this->changePasswordSnippets) {
            $params = $this->_processParameters($this->changePasswordParameters);

            $this->addSnippets($this->changePasswordSnippets, $params);
        }
    }
1172795
public function extractPublicKey($privateKey, $privateKeyPassword)
    {
        try {
            return CryptoVirgilKeyPair::extractPublicKey($privateKey, $privateKeyPassword);
        } catch (Exception $exception) {
            throw new PublicKeyExtractionException($exception->getMessage(), $exception->getCode());
        }
    }
680305
public function formatSPKey()
    {
        if (isset($this->_sp['privateKey'])) {
            $this->_sp['privateKey'] = OneLogin_Saml2_Utils::formatPrivateKey($this->_sp['privateKey']);
        }
    }
1004013
public function setPrivateKey($private_key)
    {
        // If the private key is a file name then convert it to
        // the contents of the file (which should be an RSA private
        // key in PEM format)
        if (file_exists($private_key)) {
            $this->private_key_text = file_get_contents($private_key);
        } elseif (! empty($private_key)) {
            $this->private_key_text = $private_key;
        }

        return $this;
    }
598504
public function generatePassphrase($num_words = 4)
    {
        if (count($this->dictionary) < $num_words)
        {
            throw new UnderflowException(
                "Not enough words loaded to generate a passphrase of $num_words words"
            );
        }

        $words = array();
        $attempt = 0;
        while (count($words) < $num_words)
        {
            ++$attempt;
            $s = random_int(0, count($this->dictionary) - 1);
            $word = $this->dictionary[$s];
            if (!in_array($word, $words) || $attempt > 4 * $num_words)
                $words[] = $word;
        }
        return implode(" ", $words);
    }
686861
private function encryptPrivateKey(PKEncryptionEnabledUserInterface $user)
    {
        if (!$user->isPrivateKeyEncrypted()) {
            $privateKey = $user->getPrivateKey();
            $passwordDigest = $this->getUserPasswordDigest($user);

            if ($passwordDigest) {
                $iv = $this->cryptographyProvider->generateIV(CryptographyProviderInterface::PRIVATE_KEY_ENCRYPTION);

                $keyData = new KeyData($passwordDigest, $iv);
                try {
                    $encryptedPrivateKey = $this->cryptographyProvider->encrypt(
                                    $privateKey,
                                    $keyData,
                                    CryptographyProviderInterface::PRIVATE_KEY_ENCRYPTION);

                    $encrypted = true;
                }
                catch (\Exception $ex) {
                    $encryptedPrivateKey = $privateKey;
                    $iv = null;
                    $encrypted = false;
                }
            }
            else {
                $encryptedPrivateKey = $privateKey;
                $iv = null;
                $encrypted = false;
            }

            $user->setPrivateKey($encryptedPrivateKey);
            if ($encrypted) {
                $user->setPrivateKeyIv($iv);
                $user->setPrivateKeyEncrypted(true);
            }
        }
    }
457418
public function export($keyid, $with_private = false, $passwords = array())
    {
        try {
            $key = $this->gpg->exportPublicKey($keyid, true);

            if ($with_private) {
                // GnuPG 2.1 requires secret key passphrases on export
                foreach ($passwords as $_keyid => $pass) {
                    $this->gpg->addPassphrase($_keyid, $pass);
                }

                $priv = $this->gpg->exportPrivateKey($keyid, true);
                $key .= $priv;
            }

            return $key;
        }
        catch (Exception $e) {
            return $this->get_error_from_exception($e);
        }
    }
1263185
public function encrypt($message, $userPublicKey, $userAuthToken, $regenerateKeys = false)
    {
        if (self::MAX_MESSAGE_LENGTH < strlen($message)) {
            throw new \RuntimeException(sprintf(
                'Length of message must not be greater than %d octets.', self::MAX_MESSAGE_LENGTH
            ));
        }

        // pad the message
        $message = self::padMessage($message);

        if ($regenerateKeys) {
            $this->initialize();
        }

        $userPublicKey = Base64Url::decode($userPublicKey);
        $userAuthToken = Base64Url::decode($userAuthToken);

        // get the shared secret
        $sharedSecret = $this->getSharedSecret($userPublicKey);

        $ikm = !empty($userAuthToken) ?
            self::hkdf($userAuthToken, $sharedSecret, 'Content-Encoding: auth'.chr(0), 32) :
            $sharedSecret;

        $context = $this->createContext($userPublicKey);

        // derive the Content Encryption Key
        $contentEncryptionKey = self::hkdf($this->salt, $ikm, self::createInfo('aesgcm', $context), 16);

        // derive the nonce
        $nonce = self::hkdf($this->salt, $ikm, self::createInfo('nonce', $context), 12);

        if (version_compare(PHP_VERSION, '7.1') >= 0) {
            $encryptedText = openssl_encrypt($message, 'aes-128-gcm', $contentEncryptionKey, OPENSSL_RAW_DATA, $nonce, $tag);
        } else {
            list($encryptedText, $tag) = \AESGCM\AESGCM::encrypt($contentEncryptionKey, $nonce, $message, '');
        }

        return $encryptedText.$tag;
    }
850416
public function loadKeys($configuredKeys, string $usage = null) : void
    {
        foreach ($configuredKeys as $keyData) {
            if (isset($keyData['X509Certificate'])) {
                $key = new X509($keyData);
            } else {
                $key = new Key($keyData);
            }

            if ($usage && !$key->canBeUsedFor($usage)) {
                continue;
            }

            $this->loadedKeys->add($key);
        }
    }
1162429
public function generateForgotPasswordResetToken()
    {
        $username = $this->httpRequest()->post('username');

        $token = $this->getLoginInstance()->generateDeviceValidationToken($username);
        return ['passwordResetToken' => $token];
    }
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());
    }
370547
public ParallelTaskBuilder setSshPrivKeyRelativePathWtihPassphrase(
            String privKeyRelativePath, String passphrase) {
        this.sshMeta.setPrivKeyRelativePath(privKeyRelativePath);
        this.sshMeta.setPrivKeyUsePassphrase(true);
        this.sshMeta.setPassphrase(passphrase);
        this.sshMeta.setSshLoginType(SshLoginType.KEY);
        return this;
    }
1056796
public function importPublicKeyCommand()
    {
        $keyData = '';
        // no file_get_contents here because it does not work on php://stdin
        $fp = fopen('php://stdin', 'rb');
        while (!feof($fp)) {
            $keyData .= fgets($fp, 4096);
        }
        fclose($fp);

        $fingerprint = $this->rsaWalletService->registerPublicKeyFromString($keyData);

        $this->outputLine('The public key has been successfully imported. Use the following fingerprint to refer to it in the RSAWalletService: ' . PHP_EOL . PHP_EOL . $fingerprint . PHP_EOL);
    }
323361
public function encryptPrivateKey($privateKey, $password)
    {
        try {
            return CryptoVirgilKeyPair::encryptPrivateKey($privateKey, $password);
        } catch (Exception $exception) {
            throw new PrivateKeyEncryptionException($exception->getMessage(), $exception->getCode());
        }
    }