/** * Constructor. * * @param string $username * @param Client $client * * @throws SteamLoginException In case of errors */ public function __construct($username, Client $client) { $responseBody = Utils::jsonBody($client->post(SteamLogin::STEAMCOMM_WEBSITE . '/login/getrsakey/', array('form_params' => ['donotcache' => Utils::microtime_ms(true), 'username' => $username]))); $this->publickey_mod = new BigInteger($responseBody->publickey_mod, 16); $this->publickey_exp = new BigInteger($responseBody->publickey_exp, 16); $this->timestamp = $responseBody->timestamp; $this->rsa_key = new RSA(); $this->rsa_key->setEncryptionMode(RSA::ENCRYPTION_PKCS1); $this->rsa_key->loadKey(array('e' => $this->publickey_exp, 'n' => $this->publickey_mod)); }
public function onEnable() { $this->saveDefaultConfig(); $this->saveResource("server-icon.png", false); $this->saveResource("steve.yml", false); $this->saveResource("alex.yml", false); $this->reloadConfig(); $this->onlineMode = (bool) $this->getConfig()->get("online-mode"); if ($this->onlineMode and !function_exists("mcrypt_generic_init")) { $this->onlineMode = false; $this->getLogger()->notice("no mcrypt detected, online-mode has been disabled. Try using the latest PHP binaries"); } if (!$this->getConfig()->exists("motd")) { $this->getLogger()->warning("No motd has been set. The server description will be empty."); return; } if (Info::CURRENT_PROTOCOL === 84) { $this->translator = new Translator_84(); $this->rsa = new RSA(); $this->getServer()->getPluginManager()->registerEvents($this, $this); Achievement::add("openInventory", "Taking Inventory"); //this for DesktopPlayer if ($this->onlineMode) { $this->getLogger()->info("Server is being started in the background"); $this->getLogger()->info("Generating keypair"); $this->rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1); $this->rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1); $keys = $this->rsa->createKey(1024); $this->privateKey = $keys["privatekey"]; $this->publicKey = $keys["publickey"]; $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $this->rsa->loadKey($this->privateKey); } $this->getLogger()->info("Starting Minecraft: PC server on " . ($this->getIp() === "0.0.0.0" ? "*" : $this->getIp()) . ":" . $this->getPort() . " version " . MCInfo::VERSION); $disable = true; foreach ($this->getServer()->getNetwork()->getInterfaces() as $interface) { if ($interface instanceof ProtocolInterface) { $disable = false; } } if ($disable) { $this->interface = new ProtocolInterface($this, $this->getServer(), $this->translator); $this->getServer()->getNetwork()->registerInterface($this->interface); } } else { $this->getLogger()->critical("Couldn't find a protocol translator for #" . Info::CURRENT_PROTOCOL . ", disabling plugin"); $this->getPluginLoader()->disablePlugin($this); } }
private function rsa($public_or_private_key, $padding_mode) { $rsa = new RSA(); $rsa->loadKey($public_or_private_key); $rsa->setEncryptionMode($padding_mode); return $rsa; }
public function testEncryptionModeNone() { $plaintext = 'a'; $rsa = new RSA(); $privatekey = '-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0FPqri0cb2JZfXJ/DgYSF6vUp wmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/3j+skZ6UtW+5u09lHNsj6tQ5 1s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQABAoGAFijko56+qGyN8M0RVyaRAXz++xTqHBLh 3tx4VgMtrQ+WEgCjhoTwo23KMBAuJGSYnRmoBZM3lMfTKevIkAidPExvYCdm5dYq3XToLkkLv5L2 pIIVOFMDG+KESnAFV7l2c+cnzRMW0+b6f8mR1CJzZuxVLL6Q02fvLi55/mbSYxECQQDeAw6fiIQX GukBI4eMZZt4nscy2o12KyYner3VpoeE+Np2q+Z3pvAMd/aNzQ/W9WaI+NRfcxUJrmfPwIGm63il AkEAxCL5HQb2bQr4ByorcMWm/hEP2MZzROV73yF41hPsRC9m66KrheO9HPTJuo3/9s5p+sqGxOlF L0NDt4SkosjgGwJAFklyR1uZ/wPJjj611cdBcztlPdqoxssQGnh85BzCj/u3WqBpE2vjvyyvyI5k X6zk7S0ljKtt2jny2+00VsBerQJBAJGC1Mg5Oydo5NwD6BiROrPxGo2bpTbu/fhrT8ebHkTz2epl U9VQQSQzY1oZMVX8i1m5WUTLPz2yLJIBQVdXqhMCQBGoiuSoSjafUhV7i1cEGpb88h5NBYZzWXGZ 37sJ5QsW+sJyoNde3xH8vdXhzU7eT82D6X/scw9RZz+/6rCJ4p0= -----END RSA PRIVATE KEY-----'; $rsa->loadKey($privatekey); $rsa->loadKey($rsa->getPublicKey()); $rsa->setEncryptionMode(RSA::ENCRYPTION_NONE); $expected = '105b92f59a87a8ad4da52c128b8c99491790ef5a54770119e0819060032fb9e772ed6772828329567f3d7e9472154c1530f8156ba7fd732f52ca1c06' . '5a3f5ed8a96c442e4662e0464c97f133aed31262170201993085a589565d67cc9e727e0d087e3b225c8965203b271e38a499c92fc0d6502297eca712' . '4d04bd467f6f1e7c'; $expected = pack('H*', $expected); $result = $rsa->encrypt($plaintext); $this->assertEquals($result, $expected); $rsa->loadKey($privatekey); $this->assertEquals(trim($rsa->decrypt($result), ""), $plaintext); }
/** * 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; }
public function receiveCryptoKeys($privateKey, $publicKey) { $this->privateKey = $privateKey; $this->publicKey = $publicKey; $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $this->rsa->loadKey($this->privateKey); $this->enableServer(); }
public function decrypt($encryptedToken) { defined('CRYPT_RSA_PKCS15_COMPAT') || define('CRYPT_RSA_PKCS15_COMPAT', true); $rsa = new Crypt_RSA(); $rsa->loadKey($this->privateKey); $rsa->setEncryptionMode(Crypt_RSA::ENCRYPTION_PKCS1); return $rsa->decrypt($encryptedToken); }
public function encrypt(DatabaseRow $row, User $receiver) { $rsa = new RSA(); $rsa->loadKey($receiver->getPublicKey()); $rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP); $sharedRow = clone $row; $sharedRow->setAttributes(array()); return $rsa->encrypt(json_encode($sharedRow)); }
public function login($user_id, $user_pw, $do_finalize = true) { $keys = $this->getKeys(); $rsa = new RSA(); $rsa->modulus = new BigInteger($keys['nvalue'], 16); $rsa->exponent = new BigInteger($keys['evalue'], 16); $rsa->publicExponent = new BigInteger($keys['evalue'], 16); $rsa->k = strlen($rsa->modulus->toBytes()); $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $rsa->loadKey($rsa->_convertPublicKey($rsa->modulus, $rsa->exponent), CRYPT_RSA_PRIVATE_FORMAT_PKCS1); $raw_data = $this->getLenChar($keys['sessionkey']) . $keys['sessionkey'] . $this->getLenChar($user_id) . $user_id . $this->getLenChar($user_pw) . $user_pw; $enc_data = $rsa->encrypt($raw_data); $login_url = 'https://nid.naver.com/nidlogin.login'; $headers = ['User-Agent' => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 TAKOYAKI", 'Accept' => 'text/html,application/xhtml+xml,' . 'application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding' => 'gzip, deflate', 'Referer' => 'http://www.naver.com/', 'Content-Type' => 'application/x-www-form-urlencoded']; $params = "enctp" . "=" . "1"; $params .= "&encpw" . "=" . bin2hex($enc_data); $params .= "&encnm" . "=" . $keys['keyname']; $params .= "&svctype" . "=" . "0"; $params .= "&url=http://www.naver.com/&enc_url=http%3A%2F%2Fwww.naver.com%2F&postDataKey=&nvlong=&saveID=&smart_level=undefined"; $params .= "&id" . "=" . ""; $params .= "&pw" . "=" . ""; $resp = $this->postURL($login_url, $params, 10, $headers); // echo "\n\nheader\n" . $resp ["header"] . "\n"; // echo "\n\nbody\n" . $resp ["body"] . "\n"; $this->logined = true; echo "\n로그인에 성공했습니다\n"; if (strpos($resp["body"], "새로운")) { // NEW DEVICE CHECK $key = $this->getKey($resp["body"]); $result = $this->Accept($key); $exp = explode('Set-Cookie: ', $result); $NID_SES3 = explode('Set-Cookie: NID_AUT=', $result); $work = $NID_SES3[1]; $NID_SES2 = explode(';', $work); $NID_SES = $NID_SES2[0]; $NID_AUT3 = explode('Set-Cookie: NID_AUT=', $result); $work2 = $NID_AUT3[1]; $NID_AUT2 = explode(';', $work2); $NID_AUT = $NID_AUT2[0]; $this->logined = true; echo "\n새장치 등록에 성공했습니다\n"; } elseif (strpos($resp["body"], "않습니다")) { $this->logined = false; } if ($do_finalize and strpos($resp["body"], "https://nid.naver.com/login/sso/finalize.nhn")) { $finalize_url = explode("replace(\"", $resp["body"], 2)[1]; $finalize_url = explode("\")", $finalize_url, 2)[0]; // echo "finalize_url: " . $finalize_url . "\n"; $headers = ['User-Agent' => "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0 TAKOYAKI", 'Accept' => 'text/html,application/xhtml+xml,' . 'application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' => 'ko-KR,ko;q=0.8,en-US;q=0.5,en;q=0.3', 'Accept-Encoding' => 'gzip, deflate', 'Referer' => 'https://nid.naver.com/nidlogin.login']; $resp = $this->postURL($finalize_url, $headers); echo "파이널라이즈에 성공했습니다\n"; // var_dump ( $resp ); } }
/** * Descrypts encrypted text * * @param string $ciphertext Text to decrypt * @return string Decrypted text or DECRYPTION_FAILED in case of failure */ public static function decrypt($ciphertext) { $rsa = new RSA(); $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1); $rsa->loadKey(static::getPrivateKey()); $s = new BigInteger($ciphertext, 16); // prevent library error output appearing in the dashboard set_error_handler(function () { /* ignore errors */ }); $cleartext = $rsa->decrypt($s->toBytes()); restore_error_handler(); return $cleartext; }
private function rsa($public_or_private_key, $padding_mode) { if ($public_or_private_key instanceof JOSE_JWK) { $rsa = $public_or_private_key->toKey(); } else { if ($public_or_private_key instanceof RSA) { $rsa = $public_or_private_key; } else { $rsa = new RSA(); $rsa->loadKey($public_or_private_key); } } $rsa->setEncryptionMode($padding_mode); return $rsa; }
public function addRecord(Request $request) { $rsa = new RSA(); $rsa->loadKey(Config::get('keys.private')); // private key $encryptedData = $request->input('data'); //Выставляем нужный режим декодировния $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1); //Декодируем куски текста $decryptedData = ''; foreach ($encryptedData as $encryptedDataSubstring) { $decryptedData .= $rsa->decrypt(base64_decode($encryptedDataSubstring)); } //Преобразуем декодированный текст из json массива $data = json_decode($decryptedData, true); if ($data) { //Пишем в базу только если есть данные if (array_get($data, 'data')) { Record::create($data); } } //Возвращать ничего не нужно return ''; }
/** * Login with the set username and password. * @param bool $mobile Set to true to login as a mobile user. * @param bool $relogin Set to true to force a fresh login session. * @return LoginResult * @throws SteamException Thrown when Steam gives an unexpected response (e.g. Steam is down/having issues) */ public function doLogin($mobile = false, $relogin = false) { $this->mobile = $mobile; $this->_createAuthFile(); $this->_createCookieFile(); if ($this->_isLoggedIn() && !$relogin) { if ($this->mobileAuth != null) { $this->mobileAuth->setOauth(file_get_contents($this->getAuthFilePath())); } $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']; if ($mobile) { $params['oauth_client_id'] = 'DE45CD61'; $params['oauth_scope'] = 'read_profile write_profile read_client write_client'; $params['loginfriendlyname'] = '#login_emailauth_friendlyname_mobile'; } $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']) { if (isset($loginJson['oauth'])) { file_put_contents($this->getAuthFilePath(), $loginJson['oauth']); } $this->_setSession(); $this->loggedIn = true; return LoginResult::LoginOkay; } } } } } } return LoginResult::GeneralFailure; }
/** * Decrypt with RSAES-OAEP + MGF1+SHA256 * * @param string $ciphertext * @param PrivateKey $rsaPrivateKey * @return string * @throws InvalidCiphertextException */ protected static function rsaDecrypt($ciphertext, PrivateKey $rsaPrivateKey) { static $rsa = null; if (!$rsa) { $rsa = new RSA(); $rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP); $rsa->setMGFHash('sha256'); } $rsa->loadKey($rsaPrivateKey->getKey()); $return = @$rsa->decrypt($ciphertext); if ($return === false) { throw new InvalidCiphertextException('Decryption failed'); } return $return; }
function createRsaKey($id, $pw, $sessionKey, $keyName, $eValue, $nValue) { $rsa = new RSA(); $n = $eValue; // naver~trick $e = $nValue; // switch~them $rsa->modulus = new BigInteger($n, 16); $rsa->publicExponent = new BigInteger($e, 16); $key = $rsa->getPublicKey(); $rsa->loadKey($key); $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); $comVal = $this->getLenChar($sessionKey) + $sessionKey + $this->getLenChar($id) + $id; return bin2hex($rsa->encrypt($comVal + $this->getLenChar($pw) + $pw)); }
/** * Encript a message using the user's public key. * * @author salvipascual * @param String $email * @param String $message * @return String64 * */ public function encript($email, $message) { // get the user's public key $connection = new Connection(); $res = $connection->deepQuery("SELECT publickey FROM `keys` WHERE email='{$email}'"); $publickey = $res[0]->publickey; // create the key if it does not exist if (empty($publickey)) { $keys = $this->recreateRSAKeys($email); $publickey = $keys["publickey"]; } // encript and return $rsa = new RSA(); $rsa->loadKey($publickey); $rsa->setEncryptionMode(RSA::ENCRYPTION_OAEP); return base64_encode($rsa->encrypt($message)); }