本文整理汇总了PHP中phpseclib\Crypt\RSA类的典型用法代码示例。如果您正苦于以下问题:PHP RSA类的具体用法?PHP RSA怎么用?PHP RSA使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RSA类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: executeCommand
/**
* @param string $commandName
* @param string $target
* @param array $targetConfig
* @param array $inputCommand
* @param array $userHomeDir
* @return string
*/
public function executeCommand($commandName, $target, $targetConfig, $inputCommand, $userHomeDir)
{
$remoteCommand = str_replace([sprintf('\'%s\'', $commandName), sprintf('target=\'%s\'', $target)], [$commandName, sprintf('root=%s', $targetConfig['root'])], $inputCommand);
$remoteCommand = sprintf('%s %s', $targetConfig['console'], $remoteCommand);
$key = null;
if (array_key_exists('password', $targetConfig)) {
$key = $targetConfig['password'];
}
if (!$key) {
$key = new RSA();
if (array_key_exists('passphrase', $targetConfig['keys'])) {
$passphrase = $targetConfig['keys']['passphrase'];
$passphrase = realpath(preg_replace('/~/', $userHomeDir, $passphrase, 1));
$key->setPassword(trim(file_get_contents($passphrase)));
}
$private = $targetConfig['keys']['private'];
$private = realpath(preg_replace('/~/', $userHomeDir, $private, 1));
if (!$key->loadKey(trim(file_get_contents($private)))) {
return $this->getTranslator()->trans('commands.site.debug.messages.private-key');
}
}
$ssh = new SSH2($targetConfig['host'], $targetConfig['port']);
if (!$ssh->login($targetConfig['user'], $key)) {
return sprintf('%s - %s', $ssh->getExitStatus(), $ssh->getErrors());
} else {
return $ssh->exec($remoteCommand);
}
}
示例2: factoryAuthentication
/**
* @param $config
* @return NoPasswordAuthentication|PasswordAuthentication|RSAKeyAuthentication|null
* @throws SSH2Exception
*/
protected function factoryAuthentication($config)
{
$type = $config['type'];
$username = $config['username'];
$authentication = null;
switch ($type) {
case 'password':
$password = $config['password'];
$authentication = new PasswordAuthentication($username, $password);
break;
case 'no_password':
$authentication = new NoPasswordAuthentication($username);
break;
case 'rsa':
$file = $config['file'];
$keyRSA = new RSA();
$keyRSA->loadKey(file_get_contents($file));
$authentication = new RSAKeyAuthentication($username, $keyRSA);
break;
case 'rsa_password':
$file = $config['file'];
$keyRSA = new RSA();
$keyRSA->loadKey(file_get_contents($file));
$password = $config['password'];
$keyRSA->setPassword($password);
$authentication = new RSAKeyAuthentication($username, $keyRSA);
break;
}
if (is_null($authentication)) {
throw new SSH2Exception(sprintf("No authentication for given type '%s'", $type));
}
return $authentication;
}
示例3: connect
/**
* {@inheritdoc}
*/
public function connect()
{
$this->sftp = new SFTP($this->configuration->getHost(), $this->configuration->getPort());
switch ($this->configuration->getAuthenticationMethod()) {
case ServerConfiguration::AUTH_BY_IDENTITY_FILE:
$key = new RSA();
$key->loadKey(file_get_contents($this->configuration->getPrivateKey()));
$result = $this->sftp->login($this->configuration->getUser(), $key);
break;
case ServerConfiguration::AUTH_BY_PEM_FILE:
$key = new RSA();
$key->loadKey(file_get_contents($this->configuration->getPemFile()));
$result = $this->sftp->login($this->configuration->getUser(), $key);
break;
case ServerConfiguration::AUTH_BY_AGENT:
$key = new Agent();
$result = $this->sftp->login($this->configuration->getUser(), $key);
break;
default:
throw new \RuntimeException('You need to specify authentication method.');
}
if (!$result) {
throw new \RuntimeException('Unable to login with the provided credentials.');
}
}
示例4: connect
/**
*
*/
public function connect()
{
$this->ssh = new SSH2($this->configuration['hostname'], $this->configuration['port']);
$authenticationMethod = $this->configuration[SftpDriver::CONFIG_AUTHENTICATION_METHOD];
if (static::AUTHENTICATION_PASSWORD === (int) $authenticationMethod) {
$authentication = $this->configuration['password'];
} elseif (static::AUTHENTICATION_PUBKEY === (int) $authenticationMethod) {
$authentication = new RSA();
if (!empty($this->configuration['privateKeyPassword'])) {
$authentication->setPassword($this->configuration['privateKeyPassword']);
}
$authentication->loadKey(file_get_contents($this->configuration['privateKey']));
} else {
throw new \LogicException('Wrong authentication type for phpseclibAdapter', 1476626149);
}
$sshConnected = $this->ssh->login($this->configuration['username'], $authentication);
if ($sshConnected) {
$this->sftp = new SFTP($this->configuration['hostname'], $this->configuration['port']);
$sftpConnected = $this->sftp->login($this->configuration['username'], $authentication);
if ($sftpConnected) {
$this->info['userId'] = (int) $this->ssh->exec('echo $EUID');
$this->info['groupIds'] = GeneralUtility::intExplode(' ', $this->ssh->exec('echo ${GROUPS[*]}'), true);
return true;
}
}
return false;
}
示例5: connect
/**
* Connects to remote server.
*
* @throws \InvalidArgumentException|\RuntimeException
*/
protected function connect()
{
$host = $this->gitEnvironment->getHost();
$username = $this->gitEnvironment->getUsername();
$port = $this->gitEnvironment->getPort();
$password = $this->gitEnvironment->getPassword();
$privateKey = $this->gitEnvironment->getPrivateKey();
$privateKeyPassword = $this->gitEnvironment->getPrivateKeyPassword();
$this->sftp = new SFTP($host, 22);
if (!$this->sftp) {
throw new SshLoginException(sprintf('SSH connection failed on "%s:%s"', $host, $port));
}
if (isset($username) && $privateKey != null) {
$key = new RSA();
//Set Private Key Password
if ($privateKeyPassword) {
$key->setPassword($privateKeyPassword);
}
$key->loadKey($privateKey);
//Login using private key
if (!$this->sftp->login($username, $key)) {
throw new SshLoginException(sprintf('SFTP authentication failed for user "%s" using private key', $username));
}
} else {
if (!$this->sftp->login($username, $password)) {
throw new SshLoginException(sprintf('SFTP authentication failed for user "%s" using password', $username));
}
}
}
示例6: testCrypt
/**
* A basic functional test example.
*
* @return void
*/
public function testCrypt()
{
$rsa = new RSA();
$rsa->loadKey('-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN
FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76
xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4
gwQco1KRMDSmXSMkDwIDAQAB
-----END PUBLIC KEY-----');
// public key
$plaintext = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida felis sit amet nulla accumsan, sed mollis elit tristique. Vivamus fermentum mauris et tellus feugiat luctus. Suspendisse faucibus, orci sed feugiat lobortis, nulla nunc vestibulum nibh, sed vulputate ipsum felis ac nisl. Sed sit amet est a felis posuere mollis eu placerat risus. Mauris eget nisl condimentum, varius sapien vitae, mattis nisl. Nulla porta eu nulla at imperdiet. Integer sollicitudin, ipsum nec tempus rhoncus, ipsum massa elementum sapien, ac malesuada orci augue eu nibh. Quisque posuere porttitor magna id finibus. Nunc porttitor eros et erat semper sagittis. Pellentesque sed luctus sem. Sed vulputate massa mollis lacus tincidunt auctor. Praesent aliquet quis diam sit amet rutrum. Sed mauris sem, placerat sed ex ac, hendrerit lobortis enim. Etiam egestas ex orci. Integer in varius ex, nec scelerisque tortor.';
//$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$ciphertext = $rsa->encrypt($plaintext);
$rsa->loadKey('-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ
WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR
aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB
AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv
xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH
m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd
8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF
z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5
rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM
V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe
aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil
psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz
uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876
-----END RSA PRIVATE KEY-----');
// private key
$decryptedText = $rsa->decrypt($ciphertext);
$this->assertEquals($decryptedText, $plaintext);
}
示例7: execute
/**
* {@inheritdoc }
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$privateKeyPath = $input->getOption('privateKey');
$keyBundlePath = $input->getOption('certificate');
$path = $input->getOption('path');
if (is_null($privateKeyPath) || is_null($keyBundlePath) || is_null($path)) {
$output->writeln('--privateKey, --certificate and --path are required.');
return null;
}
$privateKey = $this->fileAccessHelper->file_get_contents($privateKeyPath);
$keyBundle = $this->fileAccessHelper->file_get_contents($keyBundlePath);
if ($privateKey === false) {
$output->writeln(sprintf('Private key "%s" does not exists.', $privateKeyPath));
return null;
}
if ($keyBundle === false) {
$output->writeln(sprintf('Certificate "%s" does not exists.', $keyBundlePath));
return null;
}
$rsa = new RSA();
$rsa->loadKey($privateKey);
$x509 = new X509();
$x509->loadX509($keyBundle);
$x509->setPrivateKey($rsa);
$this->checker->writeCoreSignature($x509, $rsa, $path);
$output->writeln('Successfully signed "core"');
}
示例8: createKey
/**
* Generate a keypair
*
* @return array ['privatekey' => $privateKey, 'publickey' => $publicKey]
*/
public function createKey()
{
$rsa = new RSACrypt();
$rsa->setPublicKeyFormat(RSACrypt::PUBLIC_FORMAT_OPENSSH);
$rsa->setPassword($this->config->getSystemValue('secret', ''));
return $rsa->createKey(self::CREATE_KEY_BITS);
}
示例9: verifyIdToken
/**
* Verifies an id token and returns the authenticated apiLoginTicket.
* Throws an exception if the id token is not valid.
* The audience parameter can be used to control which id tokens are
* accepted. By default, the id token must have been issued to this OAuth2 client.
*
* @param $audience
* @return array the token payload, if successful
*/
public function verifyIdToken($idToken, $audience = null)
{
if (empty($idToken)) {
throw new LogicException('id_token cannot be null');
}
// Check signature
$certs = $this->getFederatedSignOnCerts();
foreach ($certs as $cert) {
$modulus = new BigInteger($this->jwt->urlsafeB64Decode($cert['n']), 256);
$exponent = new BigInteger($this->jwt->urlsafeB64Decode($cert['e']), 256);
$rsa = new RSA();
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
try {
$payload = $this->jwt->decode($idToken, $rsa->getPublicKey(), array('RS256'));
if (property_exists($payload, 'aud')) {
if ($audience && $payload->aud != $audience) {
return false;
}
}
// support HTTP and HTTPS issuers
// @see https://developers.google.com/identity/sign-in/web/backend-auth
$issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS);
if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) {
return false;
}
return (array) $payload;
} catch (ExpiredException $e) {
return false;
} catch (DomainException $e) {
// continue
}
}
return false;
}
示例10: connect
/**
* {@inheritdoc}
*/
public function connect()
{
$serverConfig = $this->getConfiguration();
$this->sftp = new SFTP($serverConfig->getHost(), $serverConfig->getPort(), 3600);
switch ($serverConfig->getAuthenticationMethod()) {
case Configuration::AUTH_BY_PASSWORD:
$result = $this->sftp->login($serverConfig->getUser(), $serverConfig->getPassword());
break;
case Configuration::AUTH_BY_IDENTITY_FILE:
$key = new RSA();
$key->setPassword($serverConfig->getPassPhrase());
$key->loadKey(file_get_contents($serverConfig->getPrivateKey()));
$result = $this->sftp->login($serverConfig->getUser(), $key);
break;
case Configuration::AUTH_BY_PEM_FILE:
$key = new RSA();
$key->loadKey(file_get_contents($serverConfig->getPemFile()));
$result = $this->sftp->login($serverConfig->getUser(), $key);
break;
case Configuration::AUTH_BY_AGENT:
$key = new Agent();
$key->startSSHForwarding(null);
$result = $this->sftp->login($serverConfig->getUser(), $key);
break;
default:
throw new RuntimeException('You need to specify authentication method.');
}
if (!$result) {
throw new RuntimeException('Unable to login with the provided credentials.');
}
}
示例11: handle
public function handle($data)
{
$rsa = new RSA();
$rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_XML);
$rsa->setPublicKeyFormat(RSA::PRIVATE_FORMAT_XML);
return ["assignment" => Token::generateNewToken(TOKEN_ASSIGNMENT)->toExternalForm(false)];
}
示例12: rsa
private function rsa($public_or_private_key, $padding_mode)
{
$rsa = new RSA();
$rsa->loadKey($public_or_private_key);
$rsa->setEncryptionMode($padding_mode);
return $rsa;
}
示例13: calculateSignature
/**
* Static method for quick calls to calculate a signature.
* @link https://developer.walmartapis.com/#authentication
* @param string $consumerId
* @param string $privateKey
* @param string $requestUrl
* @param string $requestMethod
* @param string|null $timestamp
* @return string
* @throws \Exception
*/
public static function calculateSignature($consumerId, $privateKey, $requestUrl, $requestMethod, $timestamp = null)
{
if (is_null($timestamp) || !is_numeric($timestamp)) {
$timestamp = self::getMilliseconds();
}
/**
* Append values into string for signing
*/
$message = $consumerId . "\n" . $requestUrl . "\n" . strtoupper($requestMethod) . "\n" . $timestamp . "\n";
/**
* Get RSA object for signing
*/
$rsa = new RSA();
$decodedPrivateKey = base64_decode($privateKey);
$rsa->setPrivateKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
$rsa->setPublicKeyFormat(RSA::PRIVATE_FORMAT_PKCS8);
/**
* Load private key
*/
if ($rsa->loadKey($decodedPrivateKey, RSA::PRIVATE_FORMAT_PKCS8)) {
/**
* Make sure we use SHA256 for signing
*/
$rsa->setHash('sha256');
$rsa->setSignatureMode(RSA::SIGNATURE_PKCS1);
$signed = $rsa->sign($message);
/**
* Return Base64 Encode generated signature
*/
return base64_encode($signed);
} else {
throw new \Exception("Unable to load private key", 1446780146);
}
}
示例14: generateKeyPair
public static function generateKeyPair($comment = 'dogpro')
{
$rsa = new RSA();
$rsa->setPublicKeyFormat(RSA::PUBLIC_FORMAT_OPENSSH);
$rsa->setComment($comment);
return $rsa->createKey();
}
示例15: doLogin
/**
* Login with the set username and password.
* @return LoginResult
* @throws SteamException Thrown when Steam gives an unexpected response (e.g. Steam is down/having issues)
* @throws \Exception Thrown when cookiefile is unable to be created.
*/
public function doLogin()
{
if (!file_exists($this->_getCookiesFilePath())) {
if (file_put_contents($this->_getCookiesFilePath(), '') === false) {
throw new \Exception("Could not create cookiefile for {$this->username}.");
}
}
if ($this->_isLoggedIn()) {
$this->loggedIn = true;
return LoginResult::LoginOkay;
}
$rsaResponse = $this->cURL('https://steamcommunity.com/login/getrsakey', null, ['username' => $this->username]);
$rsaJson = json_decode($rsaResponse, true);
if ($rsaJson == null) {
return LoginResult::GeneralFailure;
}
if (!$rsaJson['success']) {
return LoginResult::BadRSA;
}
$rsa = new RSA();
$rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
$key = ['modulus' => new BigInteger($rsaJson['publickey_mod'], 16), 'publicExponent' => new BigInteger($rsaJson['publickey_exp'], 16)];
$rsa->loadKey($key, RSA::PUBLIC_FORMAT_RAW);
$encryptedPassword = base64_encode($rsa->encrypt($this->password));
$params = ['username' => $this->username, 'password' => urlencode($encryptedPassword), 'twofactorcode' => is_null($this->twoFactorCode) ? '' : $this->twoFactorCode, 'captchagid' => $this->requiresCaptcha ? $this->captchaGID : '-1', 'captcha_text' => $this->requiresCaptcha ? $this->captchaText : '', 'emailsteamid' => $this->requires2FA || $this->requiresEmail ? (string) $this->steamId : '', 'emailauth' => $this->requiresEmail ? $this->emailCode : '', 'rsatimestamp' => $rsaJson['timestamp'], 'remember_login' => 'false'];
$loginResponse = $this->cURL('https://steamcommunity.com/login/dologin/', null, $params);
$loginJson = json_decode($loginResponse, true);
if ($loginJson == null) {
return LoginResult::GeneralFailure;
} else {
if (isset($loginJson['captcha_needed']) && $loginJson['captcha_needed']) {
$this->requiresCaptcha = true;
$this->captchaGID = $loginJson['captcha_gid'];
return LoginResult::NeedCaptcha;
} else {
if (isset($loginJson['emailauth_needed']) && $loginJson['emailauth_needed']) {
$this->requiresEmail = true;
$this->steamId = $loginJson['emailsteamid'];
return LoginResult::NeedEmail;
} else {
if (isset($loginJson['requires_twofactor']) && $loginJson['requires_twofactor'] && !$loginJson['success']) {
$this->requires2FA = true;
return LoginResult::Need2FA;
} else {
if (isset($loginJson['login_complete']) && !$loginJson['login_complete']) {
return LoginResult::BadCredentials;
} else {
if ($loginJson['success']) {
$this->_setSession();
$this->loggedIn = true;
return LoginResult::LoginOkay;
}
}
}
}
}
}
return LoginResult::GeneralFailure;
}