Exemplo n.º 1
2
function RSADecrypt($ciphertext, $privateKey)
{
    $rsad = new Crypt_RSA();
    $rsad->loadKey($privateKey);
    $rsad->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    return $rsad->decrypt(hex2bin($ciphertext));
}
Exemplo n.º 2
0
 protected function initRsa($publicKeyFile)
 {
     if (!file_exists($publicKeyFile) || !is_readable($publicKeyFile)) {
         throw new \Exception('Public key file does not exist or is not readable.');
     }
     $public_key = file_get_contents($publicKeyFile);
     $this->rsa = new \Crypt_RSA();
     $x509 = new \File_X509();
     $x509->loadX509($public_key);
     $this->rsa->loadKey($x509->getPublicKey());
     $this->rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $this->rsa->setHash('sha1');
 }
Exemplo n.º 3
0
 /**
  * @return \Crypt_RSA|null
  */
 public static function CryptRSA()
 {
     if (null === \RainLoop\Utils::$RSA) {
         if (!\defined('_phpseclib_')) {
             \set_include_path(\get_include_path() . PATH_SEPARATOR . APP_VERSION_ROOT_PATH . 'app/libraries/phpseclib');
             define('_phpseclib_', true);
         }
         if (!\class_exists('Crypt_RSA', false)) {
             include_once 'Crypt/RSA.php';
             \defined('CRYPT_RSA_MODE') || \define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL);
         }
         if (\class_exists('Crypt_RSA')) {
             $oRsa = new \Crypt_RSA();
             $oRsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
             $oRsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
             $oRsa->setPrivateKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
             $sPrivateKey = \file_exists(APP_PRIVATE_DATA . 'rsa/private') ? \file_get_contents(APP_PRIVATE_DATA . 'rsa/private') : '';
             if (!empty($sPrivateKey)) {
                 $oRsa->loadKey($sPrivateKey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
                 $oRsa->loadKey($oRsa->getPublicKey(), CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
                 \RainLoop\Utils::$RSA = $oRsa;
             }
         }
     }
     return \RainLoop\Utils::$RSA;
 }
Exemplo n.º 4
0
Arquivo: JWE.php Projeto: nask0/jose
 private function rsa($public_or_private_key, $padding_mode)
 {
     $rsa = new Crypt_RSA();
     $rsa->loadKey($public_or_private_key);
     $rsa->setEncryptionMode($padding_mode);
     return $rsa;
 }
Exemplo n.º 5
0
 private function getEncryptedPassword()
 {
     $key = $this->getRSAKey();
     $rsa = new Crypt_RSA();
     $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $rsa->loadKey(['n' => new Math_BigInteger($key->publickey_mod, 16), 'e' => new Math_BigInteger($key->publickey_exp, 16)]);
     return ['code' => base64_encode($rsa->encrypt($this->pass)), 'time' => $key->timestamp];
 }
Exemplo n.º 6
0
function encryptChallenge($publicKey, $rnd)
{
    $rsa = new Crypt_RSA();
    $rsa->loadKey($publicKey);
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $ciphertext = $rsa->encrypt($rnd);
    return base64_encode($ciphertext);
}
Exemplo n.º 7
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);
}
Exemplo n.º 8
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));
}
Exemplo n.º 9
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);
}
Exemplo n.º 10
0
 /**
  * Initializes the RSA instance using either provided private key file or default value
  * @param String $privateKeyFile Path to private key file
  * @return mixed|void
  * @throws Exception
  */
 public function initAsymmetric($privateKeyFile = '')
 {
     if (!$privateKeyFile) {
         $privateKeyFile = app_path() . '/keys/private.key';
     }
     if (!\File::exists($privateKeyFile)) {
         \Log::error("Error reading private key file.");
         throw new \Exception("Error reading private key file.");
     }
     $this->rsaPrivateKey = \File::get($privateKeyFile);
     $rsa = new \Crypt_RSA();
     $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $rsa->loadKey($this->rsaPrivateKey);
     $this->rsa = $rsa;
     $this->isRsaInitialized = true;
 }
Exemplo n.º 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;
 }
Exemplo n.º 12
0
function licenseKeyGen($userData, $privKey, $password)
{
    $rsa = new Crypt_RSA();
    $rsa->loadKey($privKey);
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $crypted = $rsa->encrypt($userData);
    // JSON->RAW Format
    $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
    $rsa->setHash('sha512');
    $signature = $rsa->sign(hash('sha512', $userData) . hash('sha512', $crypted));
    //sha512(JSON)+sha512(RAW)->RAW
    $license = ['Key1' => base64_encode($crypted), 'Key2' => base64_encode($signature)];
    $gzdata = gzencode(json_encode($license), 9);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB);
    $iv = mcrypt_create_iv($iv_size);
    $crypted_license = $iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_256, passgen($password, $iv, true), $gzdata, MCRYPT_MODE_CFB, $iv);
    return base64_encode($crypted_license);
}
Exemplo n.º 13
0
 public function encrypt()
 {
     $binaryKey = bin2hex(base64_decode(GOOGLE_DEFAULT_PUBLIC_KEY));
     $half = substr($binaryKey, 8, 256);
     $modulus = new Math_BigInteger(hex2bin($half), 256);
     $half = substr($binaryKey, 272, 6);
     $exponent = new Math_BigInteger(hex2bin($half), 256);
     $sha1 = sha1(base64_decode($googleDefaultPublicKey), true);
     $signature = "00" . bin2hex(substr($sha1, 0, 4));
     $rsa = new Crypt_RSA();
     $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_RAW);
     $rsa->loadKey(array("n" => $modulus, "e" => $exponent));
     $rsa->setPublicKey();
     $plain = "{$email}{$password}";
     $rsa->setEncryptionMode("CRYPT_RSA_ENCRYPTION_OAEP");
     $encrypted = bin2hex($rsa->encrypt($plain));
     $output = hex2bin($signature . $encrypted);
     $b64EncryptedPasswd = str_replace(array("+", "/"), array("-", "_"), mb_convert_encoding(base64_encode($output), "US-ASCII"));
     return $b64EncryptedPasswd;
 }
Exemplo n.º 14
0
 public function login($authcode = '', $twofactorcode = '')
 {
     $dologin = $this->getRSAkey();
     if ($dologin->publickey_mod && $dologin->publickey_exp && $dologin->timestamp) {
         $password = $this->config['password'];
         $rsa = new Crypt_RSA();
         $key = array('modulus' => new Math_BigInteger($dologin->publickey_mod, 16), 'publicExponent' => new Math_BigInteger($dologin->publickey_exp, 16));
         $rsa->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
         $rsa->setPublicKey($key);
         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
         $enc_password = base64_encode($rsa->encrypt($password));
         $login = $this->request('POST', 'https://steamcommunity.com/login/dologin/', array('password' => $enc_password, 'username' => $this->config['username'], 'twofactorcode' => $twofactorcode, 'emailauth' => $authcode, 'loginfriendlyname' => '', 'capatcha_text' => '', 'emailsteamid' => isset($this->accountdata['steamid']) ? $this->accountdata['steamid'] : '', 'rsatimestamp' => $dologin->timestamp, 'remember_login' => 'true', 'donotcache' => time()));
         $login = json_decode($login);
         if ($login->success == false) {
             if (isset($login->emailsteamid) && $login->emailauth_needed == true) {
                 if ($authcode == '') {
                     file_put_contents($this->config['datapath'] . '/logindata.json', json_encode(array('steamid' => $login->emailsteamid)));
                     $this->error('Please enter AUTHCODE available in your e-mail inbox (domain: ' . $login->emaildomain . ').');
                 } else {
                     $this->error('You enter bad authcode!');
                 }
             } else {
                 if ($login->requires_twofactor == true) {
                     if ($twofactorcode == '') {
                         $this->error('Please enter twofactorcode (mobile auth).');
                     } else {
                         $this->error('You enter bad twofactorcode!');
                     }
                 }
             }
         } else {
             preg_match_all('#g_sessionID\\s\\=\\s\\"(.*?)\\"\\;#si', $this->view('http://steamcommunity.com/id'), $matches);
             return array('steamid' => $login->transfer_parameters->steamid, 'sessionId' => $matches[1][0], 'cookies' => $this->cookiejarToString(file_get_contents('cookiejar.txt')));
         }
         return $login;
     } else {
         $this->error('Bad RSA!');
     }
     return $dologin;
 }
Exemplo n.º 15
0
 private function encriptar_rsa_texto($texto = "")
 {
     include 'rsa/Crypt/RSA.php';
     //pára encriptar la clave de la tc
     $rsa = new Crypt_RSA();
     $ciphered_text = FALSE;
     //if (file_exists('application/controllers/rsa/public.pem')) {
     if (file_exists('application/controllers/rsa/public_cms.pem')) {
         //se carga la 'public key'
         //$rsa->loadKey(file_get_contents('application/controllers/rsa/public.pem')); 	// public key con password "3xp4n5i0n"
         $rsa->loadKey(file_get_contents('application/controllers/rsa/public_cms.pem'));
         // public key con password "3xp4n5i0n"
         //algoritmo de encriptación
         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
         //2
         //texto cifrado:
         $ciphertext = $rsa->encrypt($texto);
         $ciphered_text = base64_encode($ciphertext);
         //texto cifrado
         //echo "texto cifrado" . $ciphertext . "<br/>";
         //texto codificado
         //echo "base 64 encode: " . base64_encode($ciphertext) . "<br/>";
     }
     return $ciphered_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);
 }
Exemplo n.º 17
0
<?php

set_time_limit(0);
if (file_exists('private.key')) {
    echo base64_encode(file_get_contents('private.key'));
} else {
    include 'Crypt/RSA.php';
    $rsa = new Crypt_RSA();
    $rsa->setHash('sha1');
    $rsa->setMGFHash('sha1');
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
    $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
    $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
    $res = $rsa->createKey(1024);
    $privateKey = $res['privatekey'];
    $publicKey = $res['publickey'];
    file_put_contents('public.key', $publicKey);
    file_put_contents('private.key', $privateKey);
    echo base64_encode($privateKey);
}
Exemplo n.º 18
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;
 }
Exemplo n.º 19
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;
}
Exemplo n.º 20
0
 public static function encrypt_value($encrypt_key_id, $value)
 {
     $encrypt_key = self::get_encrypt_key($encrypt_key_id);
     if ($encrypt_key && $encrypt_key['public_key']) {
         $dir = getcwd();
         chdir('includes/plugin_encrypt/phpseclib/');
         require_once 'Crypt/RSA.php';
         chdir($dir);
         // if encrypt fails return plain tet
         $rsa = new Crypt_RSA();
         //echo "Public Key: '".$encrypt_key['public_key']."'\n\n";
         $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_RAW);
         $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
         $public_key = array('n' => new Math_BigInteger($encrypt_key['public_key'], 16), 'e' => new Math_BigInteger($encrypt_key['e'], 16));
         $rsa->loadKey($public_key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
         $ciphertext = $rsa->encrypt($value);
         return bin2hex($ciphertext);
     }
     return false;
 }
Exemplo n.º 21
0
 /**
  * Asymmetrically encrypt a symmetrical encryption key
  *
  * @param string $triple_des_key A Triple DES (3DES) encryption key
  * @return string A base64-encoded and url-encoded representation of the $triple_des_key
  */
 private function encryptCipher($triple_des_key)
 {
     $triple_des_key_urlencoded = '';
     $rsa = new \Crypt_RSA();
     $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $rsa->loadKey($this->public_key);
     $triple_des_key_binary = $rsa->encrypt($triple_des_key);
     $triple_des_key_base64 = base64_encode($triple_des_key_binary);
     $triple_des_key_urlencoded = urlencode($triple_des_key_base64) . "decode";
     return $triple_des_key_urlencoded;
 }
Exemplo n.º 22
0
/**
 * 
 * @param string $cookies
 * @param type $encryptedPassord
 * @return boolean
 */
function steamConnect(&$cookies, &$encryptedPassword, &$rsaTime)
{
    include_once _SYSDIR_ . 'private/libs/phpseclib/Math/BigInteger.php';
    include_once _SYSDIR_ . 'private/libs/phpseclib/Crypt/RSA.php';
    $login = STEAM_LOGIN;
    $password = STEAM_PASSWORD;
    $cookies = _SYSDIR_ . 'private/cookies/cookies.txt';
    $output = geturl("https://store.steamcommunity.com", null, $cookies, null, 0, $info);
    $output = geturl("https://steamcommunity.com/login/getrsakey", null, $cookies, array('username' => $login, 'donotcache' => time()), 0, $info);
    $data = json_decode($output, true);
    if (!$data['success'] === true) {
        return false;
    }
    $publickey_exp = $data['publickey_exp'];
    $publickey_mod = $data['publickey_mod'];
    $RSA = new Crypt_RSA();
    $RSA->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $n = new Math_BigInteger($publickey_mod, 16);
    $e = new Math_BigInteger($publickey_exp, 16);
    $key = array("modulus" => $n, "publicExponent" => $e);
    $RSA->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
    $encryptedPassword = base64_encode($RSA->encrypt($password, false));
    $encryptedPassword = str_replace('/', '%2F', $encryptedPassword);
    $encryptedPassword = str_replace('+', '%2B', $encryptedPassword);
    $encryptedPassword = str_replace('=', '%3D', $encryptedPassword);
    $params = array('username' => $login, 'password' => $encryptedPassword, 'rsatimestamp' => $data['timestamp'], 'captcha_gid' => -1, 'captcha_text' => '', 'emailauth' => '', 'emailsteamid' => '');
    $rsaTime = $data['timestamp'];
    $output = geturl("https://steamcommunity.com/login/dologin/", null, $cookies, $params, 0, $info);
    return json_decode($output, true);
}
Exemplo n.º 23
0
 public function encryptPassword($email, $password)
 {
     $googleDefaultPublicKey = "AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ==";
     $binaryKey = bin2hex(base64_decode($googleDefaultPublicKey));
     $half = substr($binaryKey, 8, 256);
     $modulus = new Math_BigInteger(hex2bin($half), 256);
     $half = substr($binaryKey, 272, 6);
     $exponent = new Math_BigInteger(hex2bin($half), 256);
     $sha1 = sha1(base64_decode($googleDefaultPublicKey), true);
     $signature = "00" . bin2hex(substr($sha1, 0, 4));
     $rsa = new Crypt_RSA();
     $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_RAW);
     $rsa->loadKey(array("n" => $modulus, "e" => $exponent));
     $rsa->setPublicKey();
     $plain = "{$email}{$password}";
     $rsa->setEncryptionMode("CRYPT_RSA_ENCRYPTION_OAEP");
     $encrypted = bin2hex($rsa->encrypt($plain));
     $output = hex2bin($signature . $encrypted);
     $b64EncryptedPasswd = str_replace(array("+", "/"), array("-", "_"), mb_convert_encoding(base64_encode($output), "US-ASCII"));
     return $b64EncryptedPasswd;
 }
Exemplo n.º 24
0
 public function rsa_encrypt($input_str, $key)
 {
     $rsa = new Crypt_RSA();
     $rsa->setPrivateKeyFormat(CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
     $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_PKCS1);
     $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
     $public_key = array('n' => new Math_BigInteger($key, 16), 'e' => new Math_BigInteger('65537', 10));
     $rsa->loadKey($public_key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
     return $rsa->encrypt($input_str);
 }
Exemplo n.º 25
0
 //print_R($tx_array);
 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
Exemplo n.º 26
0
 /**
  * Encrypt data for WHMCS Member Area and License system
  *
  * The return value will be blank if anything goes wrong, otherwise it is a
  * base64 encoded value.
  *
  * NOTE: Crypt_RSA traditionally will emit warnings; the are not suppressed
  * here.
  *
  * @param array $data Key/value pairs to bundle into the encrypted string
  * @param string $publicKey RSA public key to use for the asymmetric encryption
  *
  * @return string
  */
 function encryptMemberData($data = array(), &$publicKey = '')
 {
     if (!$publicKey) {
         $publicKey = $this->getMemberPublicKey();
     }
     $publicKey = str_replace(array("\n", "\r", " "), array('', '', ''), $publicKey);
     $cipherText = '';
     if (is_array($data)) {
         try {
             $rsa = new Crypt_RSA();
             $rsa->loadKey($publicKey);
             $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
             $cipherText = $rsa->encrypt(json_encode($data));
             if (!$cipherText) {
                 throw new Exception('Could not perform rsa encryption');
             } else {
                 $cipherText = base64_encode($cipherText);
             }
         } catch (Exception $e) {
             $this->debug('Failed to encrypt member data');
         }
     }
     return $cipherText;
 }
Exemplo n.º 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;
}
Exemplo n.º 28
0
 public function get_stat_cookies()
 {
     global $current_user;
     $cookies = $this->get_auth_cookies($current_user->ID);
     $publicKey = $this->get_master_public_key();
     if (empty($cookies)) {
         return $cookies;
     }
     require_once dirname(__FILE__) . '/../../src/PHPSecLib/Crypt/RSA.php';
     $rsa = new Crypt_RSA();
     $rsa->setEncryptionMode(CRYPT_RSA_SIGNATURE_PKCS1);
     $rsa->loadKey($publicKey);
     foreach ($cookies as &$cookieValue) {
         $cookieValue = base64_encode($rsa->encrypt($cookieValue));
     }
     return $cookies;
 }
Exemplo n.º 29
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;
     }
 }
 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));
 }