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(); } }
/** * @Route("/rsa/create",name="RSA_CREATE_KEY") */ function rsaCreateKeyAction() { $form = $this->createFormBuilder()->setMethod('POST')->setAction($this->generateUrl('RSA_CREATE_KEY'))->add('Length', 'number')->add('submit', 'submit')->getForm(); $request = $this->get('request'); $form->handleRequest($request); if ($request->isXmlHttpRequest()) { $length = intval($form['Length']->getData()); $rsa = new \phpseclib\Crypt\RSA(); $key = $rsa->createKey($length); return new JsonResponse(array('public_key' => $key['publickey'], 'private_key' => $key['privatekey'])); } if ($request->getMethod() == 'POST') { $length = intval($form['Length']->getData()); $rsa = new \phpseclib\Crypt\RSA(); $key = $rsa->createKey($length); return $this->render("@Assignment1Cryptography/Crypto/RSA/createkey.html.twig", array('form' => $form->createView(), 'key' => $key)); } return $this->render("@Assignment1Cryptography/Crypto/RSA/createkey.html.twig", array('form' => $form->createView())); }
<?php include '../phpseclib/vendor/autoload.php'; $privKey = new \phpseclib\Crypt\RSA(); $private = file_get_contents('private.pem'); $privKey->setPassword('VdcpDTWTc5Aehxgv2uL9haaFddDBhrc8uCMG3ykg'); $privKey->load($private); $pubKey = new \phpseclib\Crypt\RSA(); $public = file_get_contents('public.pem'); $pubKey->load($public); $subject = new \phpseclib\File\X509(); $subject->setDNProp('id-at-organizationName', 'www.test.com'); $subject->setDNProp('name', 'Name Inc.'); $subject->setDNProp('emailaddress', '*****@*****.**'); $subject->setDNProp('postalcode', '90210'); $subject->setDNProp('state', 'California'); $subject->setDNProp('streetaddress', 'Infinite Loop 1'); $subject->setPublicKey($pubKey); $issuer = new \phpseclib\File\X509(); $issuer->setPrivateKey($privKey); $issuer->setDN($subject->getDN()); $x509 = new \phpseclib\File\X509(); $x509->setStartDate(date('Y-m-d H:i:s')); $x509->setEndDate(date('Y-m-d H:i:s', strtotime('+1 year'))); $result = $x509->sign($issuer, $subject, 'sha512WithRSAEncryption'); $certificate = $x509->saveX509($result); $filepublic = fopen('cert.crt', 'w'); fwrite($filepublic, $certificate); fclose($filepublic); echo 'Cert has been generated' . PHP_EOL; echo $certificate . PHP_EOL;
/** * @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); }
<?php include '../phpseclib/vendor/autoload.php'; $rsa = new \phpseclib\Crypt\RSA(); $private = file_get_contents('private.pem'); $rsa->setPassword('VdcpDTWTc5Aehxgv2uL9haaFddDBhrc8uCMG3ykg'); phpseclib\Crypt\RSA\PKCS1::setEncryptionAlgorithm('AES-256-CBC'); $rsa->setHash('sha512'); $rsa->setMGFHash('sha512'); $rsa->load($private); foreach ($rsa->primes as $key => $prime) { echo 'p' . $key . '= ' . $prime . '(' . strlen($prime) . ')' . PHP_EOL; } echo 'n= ' . $rsa->modulus . PHP_EOL; echo 'e= ' . $rsa->publicExponent . '(binary: ' . decbin($rsa->publicExponent->value) . ')' . '(hexadecimal: ' . dechex($rsa->publicExponent->value) . ')' . PHP_EOL; if ($rsa->password) { echo 'password= '******'Bits: ' . $rsa->getSize() . ' bits.' . '(' . strlen($rsa->modulus) . ')(2^' . $rsa->getSize() . ')' . PHP_EOL; echo PHP_EOL; echo $rsa->getPrivateKey('PKCS1') . PHP_EOL;
<?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); }
<?php include '../phpseclib/vendor/autoload.php'; $rsa = new \phpseclib\Crypt\RSA(); extract($rsa->createKey(2048)); $publickey->setHash('sha512'); $publickey->setMGFHash('sha512'); $privatekey->setHash('sha512'); $privatekey->setMGFHash('sha512'); $password = substr(base64_encode(openssl_random_pseudo_bytes(45)), 0, 32); $privatekey->setPassword($password); phpseclib\Crypt\RSA\PKCS1::setEncryptionAlgorithm('AES-256-CBC'); $fileprivate = fopen('private.pem', 'w'); fwrite($fileprivate, $privatekey->getPrivateKey('PKCS1')); fclose($fileprivate); $filepublic = fopen('public.pem', 'w'); fwrite($filepublic, $publickey->getPublicKey('PKCS1')); fclose($filepublic); echo 'Keys has been generated' . "\r\n"; echo 'Password is: ' . $password;
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; }
/** * Make the Jason API call to the backend via http */ private function make_jason_http_request($data) { // use key 'http' even if you send the request to https://... $options = array('http' => array('header' => "Content-type: application/json\r\n", 'method' => 'POST', 'content' => json_encode($data))); $context = stream_context_create($options); $result = file_get_contents(get_option('api_uri'), false, $context); $keyArray = $this->get_key(); // extract the key $modulus = $keyArray['keys'][0]['n']; $exponent = $keyArray['keys'][0]['e']; $rsa = new phpseclib\Crypt\RSA(); $modulus = new \phpseclib\Math\BigInteger(Firebase\JWT\JWT::urlsafeB64Decode($modulus), 256); $exponent = new \phpseclib\Math\BigInteger(Firebase\JWT\JWT::urlsafeB64Decode($exponent), 256); $rsa->load(array('n' => $modulus, 'e' => $exponent)); $rsa->setPublicKey(); $pubKey = $rsa->getPublicKey(); $decodedResult = $this->decode_jwt($result, $pubKey); return array($decodedResult, $result); }
/** * @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; }
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); }
/** * @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 include '../phpseclib/vendor/autoload.php'; $rsa_signer = new \phpseclib\Crypt\RSA(); $private = file_get_contents('private.pem'); $rsa_signer->setPassword('VdcpDTWTc5Aehxgv2uL9haaFddDBhrc8uCMG3ykg'); $rsa_signer->load($private); $rsa_signer->setHash('sha512'); $rsa_signer->setMGFHash('sha512'); $message = 'Litwo Ojczyzno moja, ty jesteś jak zdrowie'; $signature = $rsa_signer->sign($message, phpseclib\Crypt\RSA::PADDING_PSS); $signature_base64 = base64_encode($signature); echo 'Message: ' . $message . "\r\n"; echo 'Signature (RAW): ' . $signature . "\r\n"; echo 'Signature (base64): ' . $signature_base64 . "\r\n"; echo '------------------------------------DECODING------------------------------------------' . "\r\n"; $rsa_verifier = new \phpseclib\Crypt\RSA(); $rsa_verifier->setHash('sha512'); $rsa_verifier->setMGFHash('sha512'); $public = file_get_contents('public.pem'); $rsa_verifier->load($public); $verification = $rsa_verifier->verify($message, $signature); echo 'Verified: ' . ($verification ? 'TRUE' : 'FALSE');
/** * 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'); } } } }
$plaintext = 'This is something secret'; $password = '******'; //Create new RSA Object - private key $rsa_private = new \phpseclib\Crypt\RSA(); //Get private key (in this case content of file) $private = file_get_contents('private.pem'); //This private key is password protected, so load key $rsa_private->setPassword($password); //load the private key $rsa_private->load($private); //set hash (I chose sha512 because sha1 apparently has collisions) $rsa_private->setHash('sha512'); //set MGF hash $rsa_private->setMGFHash('sha512'); //Create new RSA Object - public key $rsa_public = new \phpseclib\Crypt\RSA(); //Get public key (in this case content of file) $public = file_get_contents('public.pem'); //load the public key $rsa_public->load($public); //set hash $rsa_public->setHash('sha512'); //set MGF hash $rsa_public->setMGFHash('sha512'); echo 'Plaintext: ' . $plaintext . PHP_EOL; //encrypt with public key and OAEP as padding $ciphertext_raw = $rsa_public->encrypt($plaintext, phpseclib\Crypt\RSA::PADDING_OAEP); echo 'Ciphertext (RAW): ' . $ciphertext_raw . PHP_EOL; //Encode as base64 for better management $ciphertext = base64_encode($ciphertext_raw); echo 'Ciphertext (base64): ' . $ciphertext . PHP_EOL;
/** * 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); }
// Remove letter part in OpenSSL version if (!preg_match('/(\\d+\\.\\d+\\.\\d+)/i', $fullVersion, $m)) { $versions[$matches[1][$i]] = $fullVersion; } else { $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>
/** * 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(); }
<?php include '../phpseclib/vendor/autoload.php'; $rsa = new \phpseclib\Crypt\RSA(); $public = file_get_contents('public.pem'); $rsa->load($public); $rsa->setHash('sha512'); $rsa->setMGFHash('sha512'); echo 'n= ' . $rsa->modulus . PHP_EOL; echo 'e= ' . $rsa->exponent . PHP_EOL; echo 'Bits: ' . $rsa->getSize() . ' bits.' . '(' . strlen($rsa->modulus) . ')' . PHP_EOL; echo PHP_EOL; echo $rsa->getPublicKey('PKCS1') . PHP_EOL;
/** * 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; }