예제 #1
2
function RSADecrypt($ciphertext, $privateKey)
{
    $rsad = new Crypt_RSA();
    $rsad->loadKey($privateKey);
    $rsad->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    return $rsad->decrypt(hex2bin($ciphertext));
}
예제 #2
0
 /**
  * Decrypts RSA-encrypted data
  * @param String $data Data to decrypt
  * @return String
  */
 public function asymmetricDecrypt($data)
 {
     if (!$this->isRsaInitialized) {
         $this->initAsymmetric();
     }
     return $this->rsa->decrypt(Base64::UrlDecode($data));
 }
 /**
  * Log user in
  */
 function login()
 {
     $params = $this->request->get('params', false);
     if ($params) {
         $rsa = new Crypt_RSA();
         $my_pub_key = ConfigOptions::getValue('frosso_auth_my_pub_key');
         $my_pri_key = ConfigOptions::getValue('frosso_auth_my_pri_key');
         $rsa->loadKey($my_pri_key);
         $decrypted_params = $rsa->decrypt($params);
         if ($decrypted_params) {
             list($email, $token, $timestamp) = explode(';', $decrypted_params);
             if ($email && $token && $timestamp) {
                 if ($token == ConfigOptions::getValue('frosso_auth_my_pri_token') && time() - 60 * 10 < $timestamp && $timestamp < time() + 60 * 10) {
                     Authentication::useProvider('FrossoProvider', false);
                     Authentication::getProvider()->initialize(array('sid_prefix' => AngieApplication::getName(), 'secret_key' => AngieApplication::getAdapter()->getUniqueKey()));
                     Authentication::getProvider()->authenticate($email);
                 } else {
                     $this->response->forbidden();
                 }
                 // token non valido
             } else {
                 $this->response->badRequest(array('message' => 'Parametri non '));
             }
             // parametri non validi
         } else {
             $this->response->badRequest(array('message' => 'Parametri non validi'));
         }
     } else {
         $this->response->badRequest(array('message' => 'Parametri non settati'));
     }
     // parametri non settati
 }
예제 #4
0
function decrypt($privatekey, $encrypted)
{
    $rsa = new Crypt_RSA();
    $encrypted = pack('H*', $encrypted);
    $rsa->loadKey($privatekey);
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    return $rsa->decrypt($encrypted);
}
예제 #5
0
function descriptografar($texto)
{
    $rsa = new Crypt_RSA();
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
    $rsa->loadKey(file_get_contents('key/rsa_private.pem'));
    return $rsa->decrypt(base64_decode($texto));
}
예제 #6
0
 /**
  * Return true if $pub_k and $pri_k encode and decode the same text
  * 
  * @param String $pub_k
  * @param String $pri_k
  * @return boolean
  */
 static function isValidKey($pub_k, $pri_k)
 {
     $plaintext = 'pippopippo';
     $rsa = new Crypt_RSA();
     $rsa->loadKey($pub_k);
     $ciphertext = $rsa->encrypt($plaintext);
     $rsa->loadKey($pri_k);
     return $plaintext == $rsa->decrypt($ciphertext);
 }
예제 #7
0
function RSA_Decrypt($ciphertext, $privateKey)
{
    // if $ciphertext come from pidCrypt.JS, then the result of RSA_Decrypt is in base64 format
    $rsa = new Crypt_RSA();
    $rsa->loadKey($privateKey);
    $ciphertext = str_replace(array("\r", "\n", ' '), '', $ciphertext);
    $ciphertext = base64_decode($ciphertext);
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    return $rsa->decrypt($ciphertext);
}
예제 #8
0
파일: tikisecure.php 프로젝트: rjsmelo/tiki
 function decrypt($cipher)
 {
     if ($this->hasKeys() == false) {
         return "";
     }
     $keys = $this->getKeys();
     $rsa = new Crypt_RSA();
     $rsa->loadKey($keys->publickey);
     $rsa->loadKey($keys->privatekey);
     return $rsa->decrypt($cipher);
 }
예제 #9
0
 public function rsa_decrypt($ciphertext)
 {
     $oldIncludePath = get_include_path();
     $include = realpath(dirname(__FILE__));
     set_include_path($include . DIRECTORY_SEPARATOR . 'CryptLib');
     include_once 'Crypt/RSA.php';
     $rsa = new Crypt_RSA();
     $rsa->loadKey($this->rsaPrivateKey);
     $plain_text = $rsa->decrypt(base64_decode($ciphertext));
     set_include_path($oldIncludePath);
     return $plain_text;
 }
예제 #10
0
 /**
  * Attempts to use the key with current passkey thus making sure that
  * passphrase works
  */
 function verify()
 {
     $rsa = new Crypt_RSA();
     $rsa->loadKey($this['notes']);
     $encrypt = $rsa->encrypt('test');
     $pack = $this->app->getPackingKey();
     if ($pack) {
         $rsa->setPassword($pack);
     }
     $rsa->loadKey($this['data']);
     $text = $rsa->decrypt($encrypt);
     // Missmatch here shouldn't happen. It would rather throw
     // exception during decrypt();
     return $text == 'test' ? 'Successful' : 'Descryption missmatch';
 }
예제 #11
0
 public function publicDecrypt($data, $publicKey)
 {
     $this->requireLibrary();
     $rsa = new Crypt_RSA();
     $rsa->setEncryptionMode(CRYPT_RSA_SIGNATURE_PKCS1);
     $rsa->loadKey($publicKey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
     $errorCatcher = new MWP_Debug_ErrorCatcher();
     $errorCatcher->register();
     $decrypted = $rsa->decrypt($data);
     $error = $errorCatcher->yieldErrorMessage(true);
     // "Decryption error" is generated by the library when the public key is not correct.
     if ($decrypted === false && $error !== 'Decryption error') {
         throw new MWP_Worker_Exception(MWP_Worker_Exception::PHPSECLIB_DECRYPT_ERROR, "Error while trying to use OpenSSL to decrypt a message.", array('error' => $error));
     }
     return $decrypted === false ? null : $decrypted;
 }
function decrypt_message($message, $asym_key)
{
    $rsa = new Crypt_RSA();
    $rij = new Crypt_Rijndael();
    // Extract the Symmetric Key
    $len = substr($message, 0, 3);
    $len = hexdec($len);
    $sym_key = substr($message, 0, $len);
    //Extract the encrypted message
    $message = substr($message, 3);
    $ciphertext = substr($message, $len);
    $ciphertext = base64_decode($ciphertext);
    // Decrypt the encrypted symmetric key
    $rsa->loadKey($asym_key);
    $sym_key = base64_decode($sym_key);
    $sym_key = $rsa->decrypt($sym_key);
    // Decrypt the message
    $rij->setKey($sym_key);
    $plaintext = $rij->decrypt($ciphertext);
    return $message;
}
예제 #13
0
function tk_decrypt($key, $crypt_data, $skip_openssl_check = FALSE)
{
    $decrypt;
    if ($skip_openssl_check == TRUE || function_exists('openssl_public_decrypt') == TRUE) {
        // Use OpenSSL if it is working
        openssl_public_decrypt($crypt_data, $decrypt, $key, OPENSSL_PKCS1_PADDING);
        if (empty($decrypt) == TRUE) {
            // OpenSSL can't decrypt this for some reason
            // Use built in Code instead
            require_once 'RSA.php';
            $rsa = new Crypt_RSA();
            $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
            $rsa->loadKey($key);
            $decrypt = $rsa->decrypt($crypt_data);
        }
    } else {
        // Use built in Code
        require_once 'RSA.php';
        $rsa = new Crypt_RSA();
        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $rsa->loadKey($key);
        $decrypt = $rsa->decrypt($crypt_data);
    }
    return $decrypt;
}
예제 #14
0
 /**
  * Return if PIN for card is valid
  *
  * @param  string $card
  * @param  int $pin
  * @return ITS SECRET
  */
 public function local_check_pin($card, $pin, $key)
 {
     global $DB, $CFG;
     try {
         if (empty($pin) || strlen($pin) < 4) {
             throw new Exception('PIN is invalid.');
         }
         $rsa = new Crypt_RSA();
         $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
         $rsa->loadKey(get_config('quiz_nitroreportpdf', 'privkey'));
         $ckey = $rsa->decrypt(base64_decode(rawurldecode($key)));
         $token = (new Parser())->parse((string) $ckey);
         if (!$token) {
             throw new Exception('The data is invalid or time expired.');
         }
         if ($token->getClaim('iss') != "NITROCARD" || $token->getClaim('aud') != "NITROCARD" || strtotime("now") >= $token->getClaim('exp') || $token->getClaim('login') != get_config('quiz_nitroreportpdf', 'apilogin') || $token->getClaim('pass') != get_config('quiz_nitroreportpdf', 'apipass') || $token->getClaim('md5') != md5(get_config('quiz_nitroreportpdf', 'pubkey'))) {
             throw new Exception('The data is invalid or time expired.');
         }
         if (empty(strip_tags($card)) || substr(strip_tags($card), 0, 9) != "NITROCARD" || strlen(strip_tags($card)) < 98 || strlen(strip_tags($card)) > 108) {
             throw new Exception('NitroCard is invalid');
         }
         $card_e = explode('.', strip_tags($card));
         if (count($card_e) != 5) {
             throw new Exception('NitroCard is invalid');
         }
         $reqdb = $DB->count_records_sql('SELECT count(fullcardid) FROM {nitrocard_cards} WHERE fullcardid="' . strip_tags($card) . '"');
         if ($reqdb == 1) {
             //local
             $reqdb2 = $DB->count_records_sql('SELECT count(fullcardid) FROM {nitrocard_cards} WHERE fullcardid="' . strip_tags($card) . '" AND pin="' . strip_tags($pin) . '"');
             if ($reqdb2 == 1) {
                 $token_allow = (new Builder())->setIssuer('NITROCARD')->setAudience('NITROCARD')->setId(substr(md5(strtotime("now")), 0, 10), true)->setIssuedAt(time())->setExpiration(time() + 60)->set('NITROCARDID', $card)->getToken();
                 $rsa = new Crypt_RSA();
                 $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
                 $rsa->loadKey(get_config('quiz_nitroreportpdf', 'privkey'));
                 $enc = base64_encode($rsa->encrypt($token_allow));
                 $loginurl = $CFG->wwwroot . '/login/index.php';
                 if (!empty($CFG->alternateloginurl)) {
                     $loginurl = $CFG->alternateloginurl;
                 }
                 $loginurl .= '?provider=nitrocard&auth=' . rawurlencode('' . $enc);
                 return $loginurl;
             } else {
                 $DB->execute('UPDATE {nitrocard_cards} SET count_to_blocked=count_to_blocked+1 WHERE fullcardid="' . strip_tags($card) . '"');
                 $reqdb3 = $DB->get_record_sql('SELECT count_to_blocked FROM {nitrocard_cards} WHERE fullcardid="' . strip_tags($card) . '"');
                 if ($reqdb3->count_to_blocked >= 3) {
                     $DB->execute('UPDATE {nitrocard_cards} SET blocked="1" WHERE fullcardid="' . strip_tags($card) . '"');
                     throw new Exception('NitroCard is blocked.');
                 }
                 throw new Exception('PIN is incorrect.');
             }
         } else {
             //remote
         }
     } catch (Exception $e) {
         setError($e->getMessage());
     }
     return false;
 }
예제 #15
0
 public function decrypt_message($message)
 {
     if (!$this->key_local) {
         throw new Exception('No decryption key has been set');
     }
     $this->ensure_crypto_loaded();
     $rsa = new Crypt_RSA();
     $rij = new Crypt_Rijndael();
     // Extract the Symmetric Key
     $len = substr($message, 0, 3);
     $len = hexdec($len);
     $sym_key = substr($message, 3, $len);
     // Extract the encrypted message
     $cipherlen = substr($message, $len + 3, 16);
     $cipherlen = hexdec($cipherlen);
     $ciphertext = substr($message, $len + 19, $cipherlen);
     $ciphertext = base64_decode($ciphertext);
     // Decrypt the encrypted symmetric key
     $rsa->loadKey($this->key_local);
     $sym_key = base64_decode($sym_key);
     $sym_key = $rsa->decrypt($sym_key);
     // Decrypt the message
     $rij->setKey($sym_key);
     return $rij->decrypt($ciphertext);
 }
require_once './Modele/class.Bd.inc.php';
require_once './Vue/class.vue.Utilisateur.inc.php';
require_once './Librairie/PhpSecLib/Crypt/RSA.php';
// =====================================================================================================================================================
// Préparation des données à fournir à la vue : Le tableau $Vue
// =====================================================================================================================================================
$rsa = new Crypt_RSA();
$PrivateKey = Bd::GetRsaPrivateKey(CRYPT_NUMRSAKEY);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->loadkey($PrivateKey);
$Vue['Message'] = "Veuillez cliquer sur le bouton Valider après avoir saisi les informations du formulaire (* : champs obligatoires)";
$Vue['Message2'] = "";
$Vue['Authentification2'] = false;
$Vue['FormModifierMotDePasseUser'] = fGetLireFichier(DIR_FORMULAIRE . "Form.ModifierMotDePasseUser.inc.php");
if (isset($_POST['AncienMotDePasse'])) {
    $AncienMotDePasse = $rsa->decrypt(base64_decode($_POST['AncienMotDePasse']));
    $NouveauMotDePasse = $rsa->decrypt(base64_decode($_POST['NouveauMotDePasse']));
    $LoginUser = $_SESSION['Login'];
    $Vue['Authentification2'] = Bd::GetMotDePasseCorrect($LoginUser, $AncienMotDePasse);
    if ($Vue['Authentification2']) {
        $GrainDeSel = "";
        while (strlen($GrainDeSel) < 20) {
            $GrainDeSel = $GrainDeSel . substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', ceil(rand(1, 62)), 1);
        }
        Bd::SetGrainDeSelUser($LoginUser, $GrainDeSelUser);
        Bd::SetMotDePasseUser($LoginUser, $NouveauMotDePasse);
        $Vue['Message2'] = "Modification du mot de passe reussie !";
    } else {
        $Vue['Message2'] = "Ancien mot de passe incorrect";
    }
}
예제 #17
0
파일: test1.php 프로젝트: garybulin/php7
if ($text != $text1) {
    $errors[] = "error in Crypt_RSA_Key class methods";
}
///////////////////////////////////////////////
// test all functionality of Crypt_RSA class
///////////////////////////////////////////////
// create Crypt_RSA object
$rsa_obj = new Crypt_RSA(array(), MATH_LIBRARY, 'check_error');
// create Crypt_RSA_KeyPair object
$key_pair = new Crypt_RSA_KeyPair(256, MATH_LIBRARY, 'check_error');
// check encrypting/decrypting function's behaviour
$params = array('enc_key' => $key_pair->getPublicKey(), 'dec_key' => $key_pair->getPrivateKey());
$rsa_obj->setParams($params);
$text = '1234567890';
$enc_text = $rsa_obj->encrypt($text);
$text1 = $rsa_obj->decrypt($enc_text);
if ($text != $text1) {
    $errors[] = "error in encrypting/decrypting functions";
}
// check signing/sign validating
$params = array('public_key' => $key_pair->getPublicKey(), 'private_key' => $key_pair->getPrivateKey());
$rsa_obj->setParams($params);
$text = '1234567890';
$sign = $rsa_obj->createSign($text);
if (!$rsa_obj->validateSign($text, $sign)) {
    $errors[] = "error in signing/sign validating functions with default hash function";
}
// check signing/sign validating with specific hash function
$params = array('hash_func' => create_function('$text', 'return 0x1234;'));
$rsa_obj->setParams($params);
$text = '1234567890';
 /**
  * The former Action 'PurgeCVVFromStoredCreditCardInfo'.
  *
  * Note! This function shouldn't output anything and shouldn't
  * call exit(), because it is called in the special Action.
  *
  * It repalces the value CVV for this credit card in the database
  * with the string "**purged**".
  * Te following values come from the form:
  *     order_id
  *     person_info_variant_id (just in case, if it is
  *         addmissible to save more than one credit card).
  * The following values are defined by them automatically:
  *     person_attribute_id (for CVV is 14)
  *     encrypted_secret_key
  *
  * The encrypted_secret_key couldn't be used at all, just to
  * generate a new blowfish key and to encrypt it.
  * But then the decryption would take much time (twice as much),
  * as it would have to call RSA decryption for two blowfish keys
  * instead of one.
  */
 function PurgeCVVFromStoredCreditCardInfo($order_id, $person_info_variant_id, $rsa_private_key)
 {
     global $application;
     //The code is not correct. Clear the value CVV.
     //It would be better to search the id by the tag in the table person_attributes.
     $perston_attribute_id = 14;
     //Gets from the base encrypted_secret_key
     //You have to get the whole order for it.
     $order_info = modApiFunc('Checkout', 'getOrderInfo', $order_id, modApiFunc("Localization", "whichCurrencyToDisplayOrderIn", $order_id), true);
     //Encrypted data should be less in volume, than not encrypted ones.
     foreach ($order_info as $key => $info_block) {
         if (is_array($info_block)) {
             if (isset($info_block['person_info_variant_id'])) {
                 //Person Info
                 if ($info_block['person_info_variant_id'] == $person_info_variant_id) {
                     //Creditcard info
                     foreach ($info_block['attr'] as $attr) {
                         if ($attr['person_attribute_id'] == $perston_attribute_id) {
                             //CVV
                             //The required encrypted blowfish key:
                             $encrypted_secret_key = $attr['encrypted_secret_key'];
                             $old_rsa_public_key_asc_format = $attr['rsa_public_key_asc_format'];
                             /*
                             If the loaded Private key and the Public key stored
                             in the database for this attribute don't match - output an
                             error message. Do not rewrite anything in the dtatabase.
                             */
                             $old_rsa_public_key_cryptrsa_format = modApiFunc("Crypto", "convert_rsa_public_key_from_asc_into_cryptrsa_format", $old_rsa_public_key_asc_format);
                             if (modApiFunc("Crypto", "rsa_do_public_key_match_private_key", $old_rsa_public_key_cryptrsa_format, $rsa_private_key) === true) {
                                 //Decrypt it and rewrite CVV with the message "**purged**":
                                 $rsa_obj = new Crypt_RSA();
                                 $decrypted_secret_key = $rsa_obj->decrypt($encrypted_secret_key, $rsa_private_key);
                                 $MessageResources =& $application->getInstance('MessageResources');
                                 $cvv_purged__msg = $MessageResources->getMessage("CHECKOUT_ORDER_INFO_CVV_PURGED_MSG");
                                 $new_value = $cvv_purged__msg;
                                 $new_value_encrypted = base64_encode(modApiFunc("Crypto", "blowfish_encrypt", $new_value, $decrypted_secret_key));
                                 $rsa_public_key_asc_format = $old_rsa_public_key_asc_format;
                                 //Save both obfuscated and encrypted value to the database
                                 modApiFunc('Checkout', 'updateOrderPersonDataAttribute', $order_id, $person_info_variant_id, $perston_attribute_id, false, $encrypted_secret_key, $rsa_public_key_asc_format, $new_value);
                                 modApiFunc('Checkout', 'updateOrderPersonDataAttribute', $order_id, $person_info_variant_id, $perston_attribute_id, true, $encrypted_secret_key, $rsa_public_key_asc_format, $new_value_encrypted);
                             } else {
                                 //              :                                  .
                                 //Output an error: the keys don't match.
                             }
                         }
                     }
                 }
             }
         }
     }
 }
// =====================================================================================================================================================
// Informations générales sur la page
// =====================================================================================================================================================
$Infos['Page']['Titre'] = "Authentification d'un utilisateur";
// =====================================================================================================================================================
// Inclusion de la vue partielle pour l'affichage du contenu principal de la page
// =====================================================================================================================================================
require_once fGetVue(__FILE__);
// =====================================================================================================================================================
// Préparation des données à fournir à la vue : Le tableau $Vue
// =====================================================================================================================================================
$rsa = new Crypt_RSA();
$PrivateKey = Bd::GetRsaPrivateKey(CRYPT_NUMRSAKEY);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$rsa->loadkey($PrivateKey);
$Login = $rsa->decrypt(base64_decode($_POST['LoginCache']));
$Passwd = $rsa->decrypt(base64_decode($_POST['PasswordCache']));
$ResultatAuthentification = Bd::GetResultAuthentification($Login, $Passwd);
if ($ResultatAuthentification != false) {
    $Vue['ResultAuthentification'] = true;
    $Vue['NomPrenom'] = $ResultatAuthentification['NomUser'] . " " . $ResultatAuthentification['PrenomUser'];
    $Vue['Sexe'] = $ResultatAuthentification['SexeUser'];
    $Vue['Type'] = $ResultatAuthentification['LibelleTypeUser'];
    //Test si le mot de passe est le mot de passe par défaut
    if ($Passwd == "x") {
        $Vue['MotDePasseInitial'] = true;
    } else {
        $Vue['MotDePasseInitial'] = false;
    }
    $Vue['DateCreationCompte'] = $ResultatAuthentification['DateCreationUser'];
    $Vue['DateDerniereConnexion'] = $ResultatAuthentification['DateDerniereConnexionUser'];
예제 #20
0
 /**
  * Decrypt the given message using the given key pair
  *
  * @param KeyPair $key
  * @param string $encryptedText
  * @return string
  */
 public function decrypt(KeyPair $key, $encryptedText)
 {
     $rsa = new \Crypt_RSA();
     $rsa->loadKey($key->getPrivateKey());
     return $rsa->decrypt($encryptedText);
 }
예제 #21
0
 /**
  * Verifies the signature of the data using the given public key.
  *
  * @param {hex string} $data the encoded data as a hex string
  * @param {string} $public_key the public key to use as a PEM encoded public key
  * @return {bool} true if the signature is valid, false otherwise
  */
 private static function verify_encrypted_hash($calculated_hash, $encrypted_hash, $public_key)
 {
     if (!isset($calculated_hash) || !isset($encrypted_hash)) {
         return false;
     }
     $rsa = new Crypt_RSA();
     $rsa->loadKey($public_key);
     $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $digest = bin2hex($rsa->decrypt(pack("H*", $encrypted_hash)));
     return $digest === $calculated_hash;
 }
예제 #22
0
 public function loginpage_hook()
 {
     global $USER, $SESSION, $CFG, $DB, $PAGE;
     if (empty($_GET['provider'])) {
         $token = (new Builder())->setIssuer('NITROCARD')->setAudience('NITROCARD')->setId(substr(md5(strtotime("now")), 0, 10), true)->setIssuedAt(time())->setExpiration(time() + 1800)->set('login', get_config('quiz_nitroreportpdf', 'apilogin'))->set('pass', get_config('quiz_nitroreportpdf', 'apipass'))->set('md5', md5(get_config('quiz_nitroreportpdf', 'pubkey')))->getToken();
         $rsa = new Crypt_RSA();
         $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
         $rsa->loadKey(get_config('quiz_nitroreportpdf', 'pubkey'));
         $enc = base64_encode($rsa->encrypt($token));
         unset($_COOKIE['nitrocardauth']);
         //LANG STRINGS FOR JS
         setcookie('nitrocardauth', '', time() - 3600, '/');
         setcookie("nitrocardauth", $enc, time() + 1800, "/");
         $PAGE->requires->jquery();
         $PAGE->requires->css(new moodle_url($CFG->wwwroot . "/auth/nitrocard/nitrocard.css"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.min.js"));
         $PAGE->requires->css(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.css"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/html5-qrcode/lib/html5-qrcode.min.js"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/jquery.json.min.js"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/jquery.jsonrpcclient.js"));
         $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/script.js"));
         $button = '<br /><br /><a href="javascript:void(0);" onclick="javascript:M.auth_nitrocard.main(\'start\');"><img src="' . new moodle_url($CFG->wwwroot . "/auth/nitrocard/login_ico.png") . '"></a><br /><br />';
         $PAGE->requires->js_init_call('M.auth_nitrocard.showbutton', array($button));
     } elseif ($_GET['provider'] == "nitrocard") {
         try {
             //LANG STRINGS FOR JS
             //	setcookie('nitrocard_lang_pleasewait', '', time() - 3600, '/');
             $PAGE->requires->jquery();
             $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.min.js"));
             $PAGE->requires->css(new moodle_url($CFG->wwwroot . "/auth/nitrocard/pgwmodal.css"));
             $PAGE->requires->js(new moodle_url($CFG->wwwroot . "/auth/nitrocard/authload.js"));
             echo '<body onload="$.fn.nitro();"></body>';
             $rsa = new Crypt_RSA();
             $rsa->setPassword(get_config('quiz_nitroreportpdf', 'passkey'));
             $rsa->loadKey(get_config('quiz_nitroreportpdf', 'pubkey'));
             $ckey = $rsa->decrypt(base64_decode($_GET['auth']));
             $token = (new Parser())->parse((string) $ckey);
             if (!$token) {
                 throw new Exception('The data is invalid or time expired.');
             }
             if ($token->getClaim('iss') != "NITROCARD" || $token->getClaim('aud') != "NITROCARD" || strtotime("now") >= $token->getClaim('exp')) {
                 throw new Exception('The data is invalid or time expired.');
             }
             if (substr(strip_tags($token->getClaim('NITROCARDID')), 0, 9) != "NITROCARD" || strlen($token->getClaim('NITROCARDID')) < 98 || strlen($token->getClaim('NITROCARDID')) > 108) {
                 throw new Exception('NitroCard is invalid');
             }
             $card_e = explode('.', $token->getClaim('NITROCARDID'));
             if (count($card_e) != 5) {
                 throw new Exception('NitroCard is invalid');
             }
             $reqdb = $DB->count_records_sql('SELECT count(fullcardid) FROM {nitrocard_cards} WHERE fullcardid="' . $token->getClaim('NITROCARDID') . '" AND userid="' . $card_e[2] . '" AND cardid="' . $card_e[3] . '"AND hash="' . $card_e[4] . '"');
             if ($reqdb == 0) {
                 throw new Exception('NitroCard is invalid');
             } else {
                 $info = $DB->get_record_sql('SELECT user FROM {nitrocard_cards} WHERE fullcardid="' . $token->getClaim('NITROCARDID') . '"');
                 $user = get_complete_user_data('id', $info->user);
                 $USER = complete_user_login($user);
                 $USER->loggedin = true;
                 $USER->site = $CFG->wwwroot;
                 redirect(new moodle_url($CFG->wwwroot));
             }
         } catch (Exception $e) {
             throw new Exception($e->getMessage());
         }
     }
 }
 /**
  * Decrypt the provided data with an RSA private key
  *
  * @param string $data Data to decrypt
  * @param bool $base64Encoded Is the provided data Base64 encoded (defaults to true)
  * @return string Unencrypted data
  */
 public function decryptRSA($data, $base64Encoded = true)
 {
     $data = $base64Encoded ? base64_decode($data) : $data;
     $decrypted = $this->crypt->decrypt($data);
     return $decrypted;
 }
예제 #24
0
 public function verifySignature($sign, $pub_key, $text)
 {
     if (function_exists('openssl_public_decrypt')) {
         openssl_public_decrypt($sign, $request_sign, $pub_key);
         $ret = $text == $request_sign;
         return $ret;
     } else {
         set_include_path(get_include_path() . PATH_SEPARATOR . self::getPluginDir() . '/modules/phpseclib');
         require_once 'Crypt/RSA.php';
         $rsa = new Crypt_RSA();
         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
         return $rsa->decrypt($sign) == $text;
     }
 }
 public function decrypt_message($message)
 {
     if (!$this->key_local) {
         throw new Exception('No decryption key has been set');
     }
     $this->ensure_crypto_loaded();
     $rsa = new Crypt_RSA();
     if (defined('UDRPC_PHPSECLIB_ENCRYPTION_MODE')) {
         $rsa->setEncryptionMode(UDRPC_PHPSECLIB_ENCRYPTION_MODE);
     }
     // Defaults to CRYPT_AES_MODE_CBC
     $rij = new Crypt_Rijndael();
     // Extract the Symmetric Key
     $len = substr($message, 0, 3);
     $len = hexdec($len);
     $sym_key = substr($message, 3, $len);
     // Extract the encrypted message
     $cipherlen = substr($message, $len + 3, 16);
     $cipherlen = hexdec($cipherlen);
     $ciphertext = substr($message, $len + 19, $cipherlen);
     $ciphertext = base64_decode($ciphertext);
     // Decrypt the encrypted symmetric key
     $rsa->loadKey($this->key_local);
     $sym_key = base64_decode($sym_key);
     $sym_key = $rsa->decrypt($sym_key);
     // Decrypt the message
     $rij->setKey($sym_key);
     return $rij->decrypt($ciphertext);
 }
예제 #26
0
 /**
  * @param      $method
  * @param      $params
  * @param      $url
  * @param      $publickey
  * @param null $oRemoteApp
  *
  * @return array|mixed
  * @throws \Exception
  */
 public static function call($method, $params, $url, $publickey, $oRemoteApp = null)
 {
     try {
         $sOldErrorhandler = set_error_handler('Slashworks\\AppBundle\\Services\\Api::errorHandler');
         if (!is_scalar($method)) {
             throw new \Exception('Method name has no scalar value');
         }
         // check
         if (is_array($params)) {
             // no keys
             $params = array_values($params);
         } else {
             throw new \Exception('Params must be given as array');
         }
         // prepares the request
         $request = array('method' => $method, 'params' => $params, 'id' => rand(1, 999));
         $request = json_encode($request);
         $rsa = new \Crypt_RSA();
         $rsa->loadKey($publickey);
         $conairKey = file_get_contents(__DIR__ . "/../Resources/private/api/keys/server/public.key");
         $aRequest = array('pkey' => $conairKey, 'data' => base64_encode($rsa->encrypt($request)));
         $sRequest = json_encode($aRequest);
         $headers = array('Content-Type: application/json');
         if ($oRemoteApp->getApiAuthType() == "http-basic") {
             $sUsername = $oRemoteApp->getApiAuthHttpUser();
             $sPassword = $oRemoteApp->getApiAuthHttpPassword();
             if (!empty($sUsername) && !empty($sPassword)) {
                 $headers[] = "Authorization: Basic " . base64_encode($oRemoteApp->getApiAuthHttpUser() . ":" . $oRemoteApp->getApiAuthHttpPassword());
             }
         }
         $oRequest = curl_init($url);
         curl_setopt($oRequest, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($oRequest, CURLOPT_TIMEOUT, 3);
         curl_setopt($oRequest, CURLOPT_POST, 1);
         curl_setopt($oRequest, CURLOPT_POSTFIELDS, $sRequest);
         curl_setopt($oRequest, CURLOPT_RETURNTRANSFER, true);
         $response = curl_exec($oRequest);
         $iHttpStatus = curl_getinfo($oRequest, CURLINFO_HTTP_CODE);
         curl_close($oRequest);
         if ($response == "") {
             throw new \Exception("No content received");
         }
         if ($iHttpStatus === 200) {
             $response = json_decode($response, true);
             if (!isset($response['data'])) {
                 throw new \Exception("Invalid response format");
             }
             $privateKey = file_get_contents(__DIR__ . "/../Resources/private/api/keys/server/private.key");
             $rsa->loadKey($privateKey);
             $data = base64_decode($response['data']);
             $decoded = $rsa->decrypt($data);
             $response['data'] = json_decode($decoded, true);
             if (!is_array($response['data'])) {
                 throw new \Exception("Invalid response format");
             }
             $response['data']['statuscode'] = $iHttpStatus;
             ApiLog::create($iHttpStatus, $oRemoteApp->getId(), $decoded);
             restore_error_handler();
             return $response['data'];
         } else {
             ApiLog::create($iHttpStatus, $oRemoteApp->getId(), $response);
             restore_error_handler();
             return array("statuscode" => $iHttpStatus, "result" => json_encode(array("status" => false, "statuscode" => $iHttpStatus, "message" => $response)));
         }
     } catch (ContextErrorException $e) {
         restore_error_handler();
         ApiLog::create(-1, $oRemoteApp->getId(), $e->getMessage());
         return array("statuscode" => $iHttpStatus, "result" => json_encode(array("status" => false, "statuscode" => -1, "message" => $e->getMessage())));
     } catch (\Exception $e) {
         restore_error_handler();
         ApiLog::create(-1, $oRemoteApp->getId(), $e->getMessage());
         return array("statuscode" => 500, "result" => json_encode(array("status" => false, "statuscode" => -1, "message" => $e->getMessage())));
     }
 }
예제 #27
0
function check_crypt_balance_range($public_key, $block_start = 0, $block_end = 0)
{
    set_decrypt_mode();
    // Figure out which decrypt method can be best used
    //Initialize objects for Internal RSA decrypt
    if ($GLOBALS['decrypt_mode'] == 2) {
        require_once 'RSA.php';
        $rsa = new Crypt_RSA();
        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    }
    if ($block_start == 0 && $block_end == 0) {
        // Find every Time Koin sent to this public Key
        $sql = "SELECT public_key_from, public_key_to, crypt_data3, attribute FROM `transaction_history` WHERE `public_key_from` = '{$public_key}' OR `public_key_to` = '{$public_key}' ";
    } else {
        // Find every TimeKoin sent to and from this public Key in a certain time range.
        // Covert block to time.
        $start_time_range = TRANSACTION_EPOCH + $block_start * 300;
        $end_time_range = TRANSACTION_EPOCH + $block_end * 300;
        $sql = "SELECT public_key_from, public_key_to, crypt_data3, attribute FROM `transaction_history` WHERE (`public_key_from` = '{$public_key}' AND `timestamp` >= '{$start_time_range}' AND `timestamp` < '{$end_time_range}')\n\t\tOR (`public_key_to` = '{$public_key}' AND `timestamp` >= '{$start_time_range}' AND `timestamp` < '{$end_time_range}')";
    }
    $sql_result = mysql_query($sql);
    $sql_num_results = mysql_num_rows($sql_result);
    $crypto_balance = 0;
    $transaction_info;
    for ($i = 0; $i < $sql_num_results; $i++) {
        $sql_row = mysql_fetch_row($sql_result);
        $public_key_from = $sql_row[0];
        $public_key_to = $sql_row[1];
        $crypt3 = $sql_row[2];
        $attribute = $sql_row[3];
        if ($attribute == "G" && $public_key_from == $public_key_to) {
            // Currency Generation
            // Decrypt transaction information
            if ($GLOBALS['decrypt_mode'] == 2) {
                $rsa->loadKey($public_key_from);
                $transaction_info = $rsa->decrypt(base64_decode($crypt3));
            } else {
                $transaction_info = tk_decrypt($public_key_from, base64_decode($crypt3), TRUE);
            }
            $transaction_amount_sent = find_string("AMOUNT=", "---TIME", $transaction_info);
            $crypto_balance += $transaction_amount_sent;
        }
        if ($attribute == "T" && $public_key_to == $public_key) {
            // Decrypt transaction information
            if ($GLOBALS['decrypt_mode'] == 2) {
                $rsa->loadKey($public_key_from);
                $transaction_info = $rsa->decrypt(base64_decode($crypt3));
            } else {
                $transaction_info = tk_decrypt($public_key_from, base64_decode($crypt3), TRUE);
            }
            $transaction_amount_sent = find_string("AMOUNT=", "---TIME", $transaction_info);
            $crypto_balance += $transaction_amount_sent;
        }
        if ($attribute == "T" && $public_key_from == $public_key) {
            // Decrypt transaction information
            $transaction_info = tk_decrypt($public_key_from, base64_decode($crypt3));
            if ($GLOBALS['decrypt_mode'] == 2) {
                $rsa->loadKey($public_key_from);
                $transaction_info = $rsa->decrypt(base64_decode($crypt3));
            } else {
                $transaction_info = tk_decrypt($public_key_from, base64_decode($crypt3), TRUE);
            }
            $transaction_amount_sent = find_string("AMOUNT=", "---TIME", $transaction_info);
            $crypto_balance -= $transaction_amount_sent;
        }
    }
    //
    // Unset variable to free up RAM
    unset($sql_result);
    return $crypto_balance;
}
예제 #28
0
파일: shop.php 프로젝트: scuba323/dcoin
 for ($i = 0; $i < sizeof($tx_array); $i++) {
     //print "{$tx_array[$i]['type']} === ".ParseData::findType('send_dc')."\n";
     // пропускаем все ненужные тр-ии
     if ($tx_array[$i]['type'] != ParseData::findType('send_dc')) {
         continue;
     }
     $tx_array[$i]['comment'] = bin2hex($tx_array[$i]['comment']);
     // сравнение данных из таблы my_dc_transactions с тем, что в блоке
     if ($tx_array[$i]['user_id'] === $row['type_id'] && $tx_array[$i]['currency_id'] === $row['currency_id'] && (double) $tx_array[$i]['amount'] === (double) $row['amount'] && $tx_array[$i]['to_user_id'] === $row['to_user_id']) {
         //print 'OK===============';
         // расшифруем коммент
         if ($row['comment_status'] == 'encrypted') {
             $rsa = new Crypt_RSA();
             $rsa->loadKey($private_key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
             $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
             $decrypted_comment = $rsa->decrypt(hextobin($row['comment']));
             //echo '$private_key='.$private_key."\n";
             //echo 'comment='.$row['comment']."\n";
             //echo '$decrypted_comment='.$decrypted_comment."\n";
             unset($rsa);
             // запишем расшифрованный коммент, чтобы потом можно было найти перевод в ручном режиме
             $decrypted_comment = filter_var($decrypted_comment, FILTER_SANITIZE_STRING);
             $decrypted_comment = str_replace(array('\'', '"'), '', $decrypted_comment);
             $decrypted_comment = $db->escape($decrypted_comment);
             $db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\t\t\t\tUPDATE `" . DB_PREFIX . $MY_PREFIX . "my_dc_transactions`\n\t\t\t\t\t\tSET  `comment` = '{$decrypted_comment}',\n\t\t\t\t\t\t\t\t`comment_status` = 'decrypted'\n\t\t\t\t\t\tWHERE `id` = {$row['id']}\n\t\t\t\t\t\t");
         } else {
             $decrypted_comment = $row['comment'];
         }
         // возможно, что чуть раньше было reduction, а это значит, что все тр-ии,
         // которые мы ещё не обработали и которые были До блока с reduction нужно принимать с учетом reduction
         // т.к. средства на нашем счете уже урезались, а  вот те, что после reduction - остались в том виде, в котором пришли
예제 #29
0
파일: api.php 프로젝트: LoveLeAnon/timekoin
        $sql = "SELECT public_key_from, public_key_to, crypt_data3, attribute FROM `transaction_history` WHERE `public_key_from` = '{$public_key}'";
        $sql_result = mysql_query($sql);
        $sql_num_results = mysql_num_rows($sql_result);
        $crypto_balance = 0;
        $transaction_info;
        for ($i = 0; $i < $sql_num_results; $i++) {
            $sql_row = mysql_fetch_row($sql_result);
            $public_key_from = $sql_row[0];
            $public_key_to = $sql_row[1];
            $crypt3 = $sql_row[2];
            $attribute = $sql_row[3];
            if ($attribute == "G" && $public_key_from == $public_key_to) {
                // Decrypt transaction information
                if ($GLOBALS['decrypt_mode'] == 2) {
                    $rsa->loadKey($public_key_from);
                    $transaction_info = $rsa->decrypt(base64_decode($crypt3));
                } else {
                    $transaction_info = tk_decrypt($public_key_from, base64_decode($crypt3), TRUE);
                }
                $transaction_amount_sent = find_string("AMOUNT=", "---TIME", $transaction_info);
                $crypto_balance += $transaction_amount_sent;
            }
        }
        echo $crypto_balance;
    }
    // End Permission Check
    // Log inbound IP activity
    log_ip("AP", scale_trigger(100));
    exit;
}
//***********************************************************************************
 private function testKeys($params)
 {
     $str = 'test string';
     if (!function_exists('openssl_public_decrypt')) {
         // зашифруем строку
         openssl_private_encrypt($str, $sign, $params['private']);
         // проверим подпись
         openssl_public_decrypt($sign, $str2, $params['public']);
         $ret = $str == $str2;
     } else {
         set_include_path(get_include_path() . PATH_SEPARATOR . WPAdm_Core::getPluginDir() . '/modules/phpseclib');
         require_once 'Crypt/RSA.php';
         // зашифруем строку
         define('CRYPT_RSA_PKCS15_COMPAT', true);
         $rsa = new Crypt_RSA();
         $rsa->loadKey($params['private']);
         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
         $ciphertext = $rsa->encrypt($str);
         // проверим подпись
         $rsa = new Crypt_RSA();
         $rsa->loadKey($params['public']);
         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
         $ret = $str == $rsa->decrypt($ciphertext);
     }
     $this->result->setResult(WPAdm_result::WPADM_RESULT_SUCCESS);
     $this->result->setData(array('match' => (int) $ret));
 }