public function connect($test = false) { if (!$this->connection or $test) { $server = $this->server; require_once 'Crypt/RSA.php'; require_once 'Net/SFTP.php'; $this->connection = new \phpseclib\Net\SFTP($server['host'], $server['port'], 10); $logged_in = false; if (isset($server['sftp_key'])) { $key = new \phpseclib\Crypt\RSA(); if (isset($server['pass']) && !empty($server['pass'])) { $key->setPassword($server['pass']); } $key->loadKey(file_get_contents($server['sftp_key'])); $logged_in = $this->connection->login($server['user'], $key); if (!$logged_in) { Helpers::error("Could not login to {$this->host}. It may be because the key requires a passphrase, which you need to specify it as the 'pass' attribute."); } } else { $logged_in = $this->connection->login($server['user'], $server['pass']); if (!$logged_in) { Helpers::error("Could not login to {$this->host}"); } } if (!$this->connection->chdir($server['path'])) { Helpers::error("Could not change the directory to {$server['path']} on {$this->host}"); } Helpers::logmessage("Connected to: {$this->host}"); $this->current_commit = $this->get_file('REVISION', true); } if ($test) { $this->disconnect(); } }
/** * Login form * @author Benjamin BALET <*****@*****.**> */ public function login() { $data['title'] = lang('session_login_title'); $data['help'] = $this->help->create_help_link('global_link_doc_page_login'); $this->load->helper('form'); $this->load->library('form_validation'); //Note that we don't receive the password as a clear string $this->form_validation->set_rules('login', lang('session_login_field_login'), 'required'); $data['last_page'] = $this->session->userdata('last_page'); if ($this->form_validation->run() === FALSE) { $data['public_key'] = file_get_contents('./assets/keys/public.pem', TRUE); $data['salt'] = $this->generateRandomString(rand(5, 20)); $data['language'] = $this->session->userdata('language'); $data['language_code'] = $this->session->userdata('language_code'); $this->session->set_userdata('salt', $data['salt']); $data['flash_partial_view'] = $this->load->view('templates/flash', $data, TRUE); $this->load->view('templates/header', $data); $this->load->view('session/login', $data); $this->load->view('templates/footer'); } else { $this->load->model('users_model'); //Set language $this->session->set_userdata('language_code', $this->input->post('language')); $this->session->set_userdata('language', $this->polyglot->code2language($this->input->post('language'))); //Decipher the password value (RSA encoded -> base64 -> decode -> decrypt) and remove the salt! require_once APPPATH . 'third_party/phpseclib/vendor/autoload.php'; $rsa = new phpseclib\Crypt\RSA(); $private_key = file_get_contents('./assets/keys/private.pem', TRUE); $rsa->setEncryptionMode(phpseclib\Crypt\RSA::ENCRYPTION_PKCS1); $rsa->loadKey($private_key, phpseclib\Crypt\RSA::PRIVATE_FORMAT_PKCS1); $password = $rsa->decrypt(base64_decode($this->input->post('CipheredValue'))); //Remove the salt $len_salt = strlen($this->session->userdata('salt')) * -1; $password = substr($password, 0, $len_salt); $loggedin = FALSE; if ($this->config->item('ldap_enabled')) { if ($password != "") { //Bind to MS-AD with blank password might return OK $ldap = ldap_connect($this->config->item('ldap_host'), $this->config->item('ldap_port')); ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3); set_error_handler(function () { /* ignore errors */ }); if ($this->config->item('ldap_basedn_db')) { $basedn = $this->users_model->getBaseDN($this->input->post('login')); } else { $basedn = sprintf($this->config->item('ldap_basedn'), $this->input->post('login')); } $bind = ldap_bind($ldap, $basedn, $password); restore_error_handler(); if ($bind) { $loggedin = $this->users_model->checkCredentialsLDAP($this->input->post('login')); } ldap_close($ldap); } } else { $loggedin = $this->users_model->checkCredentials($this->input->post('login'), $password); } if ($loggedin == FALSE) { log_message('error', '{controllers/session/login} Invalid login id or password for user='******'login')); $this->session->set_flashdata('msg', lang('session_login_flash_bad_credentials')); $data['public_key'] = file_get_contents('./assets/keys/public.pem', TRUE); $data['salt'] = $this->generateRandomString(rand(5, 20)); $data['language'] = $this->session->userdata('language'); $data['language_code'] = $this->session->userdata('language_code'); $this->session->set_userdata('salt', $data['salt']); $data['flash_partial_view'] = $this->load->view('templates/flash', $data, TRUE); $this->load->view('templates/header', $data); $this->load->view('session/login', $data); $this->load->view('templates/footer'); } else { //If the user has a target page (e.g. link in an e-mail), redirect to this destination if ($this->session->userdata('last_page') != '') { if (strpos($this->session->userdata('last_page'), 'index.php', strlen($this->session->userdata('last_page')) - strlen('index.php'))) { $this->session->set_userdata('last_page', base_url() . 'home'); } if ($this->session->userdata('last_page_params') == '') { redirect($this->session->userdata('last_page')); } else { redirect($this->session->userdata('last_page') . '?' . $this->session->userdata('last_page_params')); } } else { redirect(base_url() . 'home'); } } } }
$versions[$matches[1][$i]] = $m[0]; } } } echo "<tr><td>PHP_VERSION</td><td>" . (version_compare(PHP_VERSION, '4.2.0', '>=') ? '>=4.2.0' : '<4.2.0') . '</td></tr>'; echo "<tr><td>openssl</td><td>" . (extension_loaded('openssl') ? 'extension loaded' : 'extension not loaded') . '</td></tr>'; echo "<tr><td>openssl_pkey_get_details</td><td>" . (function_exists('openssl_pkey_get_details') ? 'exists' : 'doesn\'t exist') . '</td></tr>'; echo "<tr><td>Private key</td><td>" . ($privateKey != '' ? 'Found' : 'Not found') . '</td></tr>'; echo "<tr><td>Public key</td><td>" . ($publicKey != '' ? 'Found' : 'Not found') . '</td></tr>'; echo "<tr><td>OpenSSL Library</td><td>" . (isset($versions['Library']) ? $versions['Library'] : 'Not found') . '</td></tr>'; echo "<tr><td>OpenSSL Header</td><td>" . (isset($versions['Header']) ? $versions['Header'] : 'Not found') . '</td></tr>'; $rsa = new \phpseclib\Crypt\RSA(); echo "<tr><td>CRYPT_RSA_MODE</td><td>" . (CRYPT_RSA_MODE == 1 ? 'MODE_INTERNAL' : 'MODE_OPENSSL') . '</td></tr>'; $rsa->setEncryptionMode(phpseclib\Crypt\RSA::ENCRYPTION_PKCS1); $plaintext = 'Jorani is the best open source Leave Management System'; $rsa->loadKey($publicKey); $ciphertext = $rsa->encrypt($plaintext); $rsa->loadKey($privateKey, phpseclib\Crypt\RSA::PRIVATE_FORMAT_PKCS1); $time_start = microtime(true); echo "<tr><td>Decrypted message</td><td>" . $rsa->decrypt($ciphertext) . '</td></tr>'; $time_end = microtime(true); $time = $time_end - $time_start; echo "<tr><td>Decryption speed</td><td>" . $time . '</td></tr>'; //Generate public and private keys for a single usage extract($rsa->createKey(KEY_SIZE)); ?> </tbody> </table> <h2 id="pair">Private and public key pair</h2>
/** * Update a given user in the database. Update data are coming from an HTML form * @return int number of affected rows * @author Benjamin BALET <*****@*****.**> */ public function resetPassword($id, $CipheredNewPassword) { //Decipher the password value (RSA encoded -> base64 -> decode -> decrypt) require_once APPPATH . 'third_party/phpseclib/vendor/autoload.php'; $rsa = new phpseclib\Crypt\RSA(); $private_key = file_get_contents('./assets/keys/private.pem', TRUE); $rsa->setEncryptionMode(phpseclib\Crypt\RSA::ENCRYPTION_PKCS1); $rsa->loadKey($private_key, phpseclib\Crypt\RSA::PRIVATE_FORMAT_PKCS1); $password = $rsa->decrypt(base64_decode($CipheredNewPassword)); //Hash the clear password using bcrypt (8 iterations) $salt = '$2a$08$' . substr(strtr(base64_encode($this->getRandomBytes(16)), '+', '.'), 0, 22) . '$'; $hash = crypt($password, $salt); $data = array('password' => $hash); $this->db->where('id', $id); return $this->db->update('users', $data); }
public function decrypt() { $rsa = new \phpseclib\Crypt\RSA(); $rsa->loadKey($this->key); $ciphertext = file_get_contents($this->getFileUploadDir() . '/' . $this->file_name); $plaintext = $rsa->decrypt($ciphertext); $hash = md5($plaintext); $this->save_name = 'DecryptedFile_' . $hash; file_put_contents($this->getFileRootDir() . '/' . $this->save_name, $plaintext); unlink($this->file->getPathname()); return new CryptoFile($hash, $this->getWebPath() . '/' . $this->save_name); }
/** * Método que obtiene la clave asociada al módulo y exponente entregados * @param modulus Módulo de la clave * @param exponent Exponente de la clave * @return Entrega la clave asociada al módulo y exponente * @author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl) * @version 2015-09-19 */ public static function getFromModulusExponent($modulus, $exponent) { $rsa = new \phpseclib\Crypt\RSA(); $modulus = new \phpseclib\Math\BigInteger(base64_decode($modulus), 256); $exponent = new \phpseclib\Math\BigInteger(base64_decode($exponent), 256); $rsa->loadKey(['n' => $modulus, 'e' => $exponent]); $rsa->setPublicKey(); return $rsa->getPublicKey(); }
/** * @param string $hashtype * @param object $key * @throws OpenIDConnectClientException * @return bool */ private function verifyRSAJWTsignature($hashtype, $key, $payload, $signature) { if (!class_exists('\\phpseclib\\Crypt\\RSA')) { throw new OpenIDConnectClientException('Crypt_RSA support unavailable.'); } if (!(property_exists($key, 'n') and property_exists($key, 'e'))) { throw new OpenIDConnectClientException('Malformed key object'); } /* We already have base64url-encoded data, so re-encode it as regular base64 and use the XML key format for simplicity. */ $public_key_xml = "<RSAKeyValue>\r\n" . " <Modulus>" . b64url2b64($key->n) . "</Modulus>\r\n" . " <Exponent>" . b64url2b64($key->e) . "</Exponent>\r\n" . "</RSAKeyValue>"; $rsa = new \phpseclib\Crypt\RSA(); $rsa->setHash($hashtype); $rsa->loadKey($public_key_xml, \phpseclib\Crypt\RSA::PUBLIC_FORMAT_XML); $rsa->signatureMode = \phpseclib\Crypt\RSA::SIGNATURE_PKCS1; return $rsa->verify($payload, $signature); }
/** * @param array $input * @param array $errors * @param array $options */ private function process_standard_options(&$input, &$errors, &$options) { if (empty($input[LaunchKey_WP_Options::OPTION_ROCKET_KEY])) { $errors[] = $this->wp_facade->__('Rocket Key is a required field', $this->language_domain); } else { $rocket_key = trim($input[LaunchKey_WP_Options::OPTION_ROCKET_KEY]); if (!is_numeric($rocket_key)) { $errors[] = $this->wp_facade->__('Rocket Key must be numeric', $this->language_domain); } elseif (strlen($rocket_key) !== 10) { $errors[] = $this->wp_facade->__('Rocket Key must be 10 digits', $this->language_domain); } else { $options[LaunchKey_WP_Options::OPTION_ROCKET_KEY] = $rocket_key; } } if (empty($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]) && empty($options[LaunchKey_WP_Options::OPTION_SECRET_KEY])) { $errors[] = $this->wp_facade->__('Secret Key is a required field', $this->language_domain); } else { if (!empty($input[LaunchKey_WP_Options::OPTION_SECRET_KEY])) { $secret_key = trim($input[LaunchKey_WP_Options::OPTION_SECRET_KEY]); if (!ctype_alnum($secret_key)) { $errors[] = $this->wp_facade->__('Secret Key must be alphanumeric', $this->language_domain); } elseif (strlen($secret_key) !== 32) { $errors[] = $this->wp_facade->__('Secret Key must be 32 characters', $this->language_domain); } else { $options[LaunchKey_WP_Options::OPTION_SECRET_KEY] = $secret_key; } } } $app_display_name = isset($input[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME]) ? trim($input[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME]) : null; if ('LaunchKey' !== $app_display_name && LaunchKey_WP_Implementation_Type::WHITE_LABEL !== $options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE]) { $errors[] = $this->wp_facade->__('App Display Name can only be modified for White Label implementations', $this->language_domain); $options[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME] = 'LaunchKey'; } else { $options[LaunchKey_WP_Options::OPTION_APP_DISPLAY_NAME] = $app_display_name ?: null; } if (empty($_FILES['private_key']['tmp_name']) && empty($options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY]) && isset($options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE]) && LaunchKey_WP_Implementation_Type::requires_private_key($options[LaunchKey_WP_Options::OPTION_IMPLEMENTATION_TYPE])) { $errors[] = $this->wp_facade->__('Private Key is required', $this->language_domain); } else { if (!empty($_FILES['private_key']['tmp_name'])) { $private_key = @file_get_contents($_FILES['private_key']['tmp_name']); $rsa = new \phpseclib\Crypt\RSA(); if (@$rsa->loadKey($private_key)) { if ($rsa->getPrivateKey($rsa->privateKeyFormat)) { $options[LaunchKey_WP_Options::OPTION_PRIVATE_KEY] = $private_key; } else { $errors[] = $this->wp_facade->__('The Key file provided was a valid RSA key file but did not contain a private key. Did you mistakenly supply the public key file?', $this->language_domain); } } else { $errors[] = $this->wp_facade->__('The Private Key provided was invalid', $this->language_domain); } } } }
<?php require_once dirname(__FILE__) . '/../lib/openpgp.php'; require_once dirname(__FILE__) . '/../lib/openpgp_crypt_rsa.php'; $rsa = new \phpseclib\Crypt\RSA(); $k = $rsa->createKey(512); $rsa->loadKey($k['privatekey']); $nkey = new OpenPGP_SecretKeyPacket(array('n' => $rsa->modulus->toBytes(), 'e' => $rsa->publicExponent->toBytes(), 'd' => $rsa->exponent->toBytes(), 'p' => $rsa->primes[2]->toBytes(), 'q' => $rsa->primes[1]->toBytes(), 'u' => $rsa->coefficients[2]->toBytes())); $uid = new OpenPGP_UserIDPacket('Test <*****@*****.**>'); $wkey = new OpenPGP_Crypt_RSA($nkey); $m = $wkey->sign_key_userid(array($nkey, $uid)); // Serialize private key print $m->to_bytes(); // Serialize public key message $pubm = clone $m; $pubm[0] = new OpenPGP_PublicKeyPacket($pubm[0]); $public_bytes = $pubm->to_bytes();
/** * Desencriptar datos cifrados con la clave pública * * @param string $data los datos a desencriptar * @return string */ public function decryptRSA($data) { $Rsa = new \phpseclib\Crypt\RSA(); $Rsa->setEncryptionMode(\phpseclib\Crypt\RSA::ENCRYPTION_PKCS1); $Rsa->loadKey($this->getPrivateKey()); return $Rsa->decrypt($data); }
static function encryptResponse($handshake, $response) { //setup encryption engine with servers keys $privateKey = Session::get("serverPrivate"); $serverAES = Session::get('serverAES'); $rsa = new \phpseclib\Crypt\RSA(); $rsa->setEncryptionMode($rsa::ENCRYPTION_PKCS1); //decrypt the clients AESkey from the $rsa->loadKey($privateKey); $clientAESkey = $rsa->decrypt(base64_decode($handshake)); //use AES to encrypt the data $AESEncrypted = cryptAES::enc($response, $clientAESkey); return $AESEncrypted; }
/** * @return \phpseclib\Crypt\RSA */ public function getKey($renew = false) { static $key = null; if ($renew || !isset($key)) { $key = new \phpseclib\Crypt\RSA(); $key->loadKey(file_get_contents($this->so->getSettings()->getPemPath()), \phpseclib\Crypt\RSA::PUBLIC_FORMAT_PKCS1); } return $key; }
/** * Update a given user in the database. Update data are coming from an * HTML form * @return type * @author Benjamin BALET <*****@*****.**> */ public function reset_password($id, $CipheredNewPassword) { //log_message('debug', '{models/users_model/reset_password} Entering function id=' . $id . ' / Ciphered password='******'bcrypt'); //Decipher the password value (RSA encoded -> base64 -> decode -> decrypt) require_once APPPATH . 'third_party/phpseclib/vendor/autoload.php'; $rsa = new phpseclib\Crypt\RSA(); $private_key = file_get_contents('./assets/keys/private.pem', true); $rsa->setEncryptionMode(phpseclib\Crypt\RSA::ENCRYPTION_PKCS1); $rsa->loadKey($private_key, phpseclib\Crypt\RSA::PRIVATE_FORMAT_PKCS1); $password = $rsa->decrypt(base64_decode($CipheredNewPassword)); log_message('debug', '{models/users_model/reset_password} Password='******'debug', '{models/users_model/reset_password} Hash=' . $hash); $data = array('password' => $hash); $this->db->where('id', $id); $result = $this->db->update('users', $data); return $result; }