/**
  * Encrypts data using RSA
  * @param String $data Data to encrypt
  * @return String
  */
 public function asymmetricEncrypt($data)
 {
     if (!$this->isRsaInitialized) {
         $this->initAsymmetric();
     }
     return Base64::UrlEncode($this->rsa->encrypt($data));
 }
示例#2
0
function RSA_Encrypt($plaintext, $publicKey)
{
    $rsa = new Crypt_RSA();
    $rsa->loadKey($publicKey);
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    return base64_encode($rsa->encrypt($plaintext));
}
function encrypt_message($plaintext, $asym_key, $key_length = 150)
{
    $rsa = new Crypt_RSA();
    $rij = new Crypt_Rijndael();
    // Generate Random Symmetric Key
    $sym_key = crypt_random_string($key_length);
    // Encrypt Message with new Symmetric Key
    $rij->setKey($sym_key);
    $ciphertext = $rij->encrypt($plaintext);
    $ciphertext = base64_encode($ciphertext);
    // Encrypted the Symmetric Key with the Asymmetric Key
    $rsa->loadKey($asym_key);
    $sym_key = $rsa->encrypt($sym_key);
    // Base 64 encode the symmetric key for transport
    $sym_key = base64_encode($sym_key);
    $len = strlen($sym_key);
    // Get the length
    $len = dechex($len);
    // The first 3 bytes of the message are the key length
    $len = str_pad($len, 3, '0', STR_PAD_LEFT);
    // Zero pad to be sure.
    // Concatinate the length, the encrypted symmetric key, and the message
    $message = $len . $sym_key . $ciphertext;
    return $message;
}
示例#4
0
    public function testSuppliedKey()
    {
        // $ openssl genrsa -out key.pem 512
        $generatedKey = <<<EOL
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAKihibtt92M6A/z49CqNcWugBd3sPrW3HF8TtKANZd1EWQ/agZ65
H2/NdL8H6zCgmKpYFTqFGwlYrnWrsbD1UxcCAwEAAQJAWX5pl1Q0D7Axf6csBg1M
3V5u3qlLWqsUXo0ZtjuGDRgk5FsJOA9bkxfpJspbr2CFkodpBuBCBYpOTQhLUc2H
MQIhAN1stwI2BIiSBNbDx2YiW5IVTEh/gTEXxOCazRDNWPQJAiEAwvZvqIQLexer
TnKj7q+Zcv4G2XgbkhtaLH/ELiA/Fh8CIQDGIC3M86qwzP85cCrub5XCK/567GQc
GmmWk80j2KpciQIhAI/ybFa7x85Gl5EAS9F7jYy9ykjeyVyDHX0liK+V1355AiAG
jU6zr1wG9awuXj8j5x37eFXnfD/p92GpteyHuIDpog==
-----END RSA PRIVATE KEY-----
EOL;
        // $ openssl rsa -pubout -in key.pem
        $publickey = <<<EOL
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKihibtt92M6A/z49CqNcWugBd3sPrW3
HF8TtKANZd1EWQ/agZ65H2/NdL8H6zCgmKpYFTqFGwlYrnWrsbD1UxcCAwEAAQ==
-----END PUBLIC KEY-----
EOL;
        $rsa = new Crypt_RSA();
        $rsa->loadKey($publickey);
        $str = "123";
        $enc = $rsa->encrypt($str);
        //        echo "encoded=",bin2hex($enc),"\n";
        $rsa->loadKey($generatedKey);
        $dec = $rsa->decrypt($enc);
        $this->assertEquals($str, $dec, "Basic Encrypt/Decrypt with Supplied key.");
    }
示例#5
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);
}
示例#6
0
文件: User.php 项目: Top-Cat/EscrowTF
 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];
 }
示例#7
0
function criptografar($texto)
{
    $rsa = new Crypt_RSA();
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
    $rsa->loadKey($_SESSION['chave_publica']);
    return base64_encode($rsa->encrypt($texto));
}
示例#8
0
function RSAEncrypt($text, $pem)
{
    $x509 = new File_X509();
    $rsa = new Crypt_RSA();
    $x509->loadX509($pem);
    $rsa->loadKey($x509->getPublicKey());
    $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
    return bin2hex($rsa->encrypt($text));
}
示例#9
0
 function encrypt($data = "")
 {
     $keys = $this->getKeys();
     $path = get_include_path();
     $rsa = new Crypt_RSA();
     $rsa->loadKey($keys->publickey);
     set_include_path($path);
     return $rsa->encrypt($data);
 }
 /**
  * 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);
 }
 /**
  * Index action
  */
 function index()
 {
     $rsa = new Crypt_RSA();
     $rsa->loadKey(ConfigOptions::getValue('frosso_auth_my_pub_key'));
     $text = 'frosso@remedia.it;' . ConfigOptions::getValue('frosso_auth_my_pri_token', false) . ';' . time();
     $crypt = $rsa->encrypt($text);
     echo '<textarea cols="200">' . $crypt . "</textarea>";
     echo '<br/><textarea cols="200">' . urlencode($crypt) . "</textarea>";
     $this->response->badRequest();
 }
示例#12
0
 function encrypt($data = "")
 {
     $keys = $this->getKeys();
     $path = get_include_path();
     set_include_path("lib/phpseclib/");
     require_once 'Crypt/RSA.php';
     $rsa = new Crypt_RSA();
     $rsa->loadKey($keys->privatekey);
     set_include_path($path);
     return $rsa->encrypt($data);
 }
示例#13
0
 public function rsa_encrypt($plain_text, $publicKey)
 {
     $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($publicKey);
     $ciphertext = $rsa->encrypt($plain_text);
     set_include_path($oldIncludePath);
     return base64_encode($ciphertext);
 }
示例#14
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';
 }
 public function publicEncrypt($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();
     $encrypted = $rsa->encrypt($data);
     $error = $errorCatcher->yieldErrorMessage(true);
     if ($encrypted === false && $error !== null) {
         throw new MWP_Worker_Exception(MWP_Worker_Exception::PHPSECLIB_ENCRYPT_ERROR, "Error while trying to use OpenSSL to encrypt a message.", array('error' => $error));
     }
     return $encrypted;
 }
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);
}
示例#17
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;
 }
示例#18
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;
 }
示例#19
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);
 }
 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;
 }
示例#21
0
 public function encrypt_message($plaintext, $use_key = false, $key_length = 150)
 {
     if (!$use_key && !$this->key_local) {
         throw new Exception('No encryption key has been set');
     }
     if (!$use_key) {
         $use_key = $this->key_local;
     }
     $this->ensure_crypto_loaded();
     $rsa = new Crypt_RSA();
     $rij = new Crypt_Rijndael();
     // Generate Random Symmetric Key
     $sym_key = crypt_random_string($key_length);
     // Encrypt Message with new Symmetric Key
     $rij->setKey($sym_key);
     $ciphertext = $rij->encrypt($plaintext);
     $ciphertext = base64_encode($ciphertext);
     // Encrypted the Symmetric Key with the Asymmetric Key
     $rsa->loadKey($use_key);
     $sym_key = $rsa->encrypt($sym_key);
     // Base 64 encode the symmetric key for transport
     $sym_key = base64_encode($sym_key);
     $len = str_pad(dechex(strlen($sym_key)), 3, '0', STR_PAD_LEFT);
     // Zero pad to be sure.
     // 16 characters of hex is enough for the payload to be to 16 exabytes (giga < tera < peta < exa) of data
     $cipherlen = str_pad(dechex(strlen($ciphertext)), 16, '0', STR_PAD_LEFT);
     // Concatenate the length, the encrypted symmetric key, and the message
     return $len . $sym_key . $cipherlen . $ciphertext;
 }
 public function encrypt_message($plaintext, $use_key = false, $key_length = 32)
 {
     if (!$use_key) {
         if ($this->format == 1) {
             if (!$this->key_local) {
                 throw new Exception('No encryption key has been set');
             }
             $use_key = $this->key_local;
         } else {
             if (!$this->key_remote) {
                 throw new Exception('No encryption key has been set');
             }
             $use_key = $this->key_remote;
         }
     }
     $this->ensure_crypto_loaded();
     $rsa = new Crypt_RSA();
     if (defined('UDRPC_PHPSECLIB_ENCRYPTION_MODE')) {
         $rsa->setEncryptionMode(UDRPC_PHPSECLIB_ENCRYPTION_MODE);
     }
     $rij = new Crypt_Rijndael();
     // Generate Random Symmetric Key
     $sym_key = crypt_random_string($key_length);
     if ($this->debug) {
         $this->log('Unencrypted symmetric key (hex): ' . bin2hex($sym_key));
     }
     // Encrypt Message with new Symmetric Key
     $rij->setKey($sym_key);
     $ciphertext = $rij->encrypt($plaintext);
     if ($this->debug) {
         $this->log('Encrypted ciphertext (hex): ' . bin2hex($ciphertext));
     }
     $ciphertext = base64_encode($ciphertext);
     // Encrypt the Symmetric Key with the Asymmetric Key
     $rsa->loadKey($use_key);
     $sym_key = $rsa->encrypt($sym_key);
     if ($this->debug) {
         $this->log('Encrypted symmetric key (hex): ' . bin2hex($sym_key));
     }
     // Base 64 encode the symmetric key for transport
     $sym_key = base64_encode($sym_key);
     if ($this->debug) {
         $this->log('Encrypted symmetric key (b64): ' . $sym_key);
     }
     $len = str_pad(dechex(strlen($sym_key)), 3, '0', STR_PAD_LEFT);
     // Zero pad to be sure.
     // 16 characters of hex is enough for the payload to be to 16 exabytes (giga < tera < peta < exa) of data
     $cipherlen = str_pad(dechex(strlen($ciphertext)), 16, '0', STR_PAD_LEFT);
     // Concatenate the length, the encrypted symmetric key, and the message
     return $len . $sym_key . $cipherlen . $ciphertext;
 }
示例#23
0
文件: test1.php 项目: garybulin/php7
$text1 = $rsa_obj->decrypt($enc_text, $private_key);
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);
示例#24
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;
 }
示例#25
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;
 }
 /**
  * Adds a Custoner (List Person) to this order.
  * It is used, for example, to save unregistered customers.
  * A separate record is not created in the table persons.
  *
  * @
  * @param
  * @return
  */
 function addOrderPerson($order_id)
 {
     global $application;
     $tables = $this->getTables();
     $ptiv = $tables["person_to_info_variants"]['columns'];
     $opd = $tables["order_person_data"]['columns'];
     $data = $this->getPrerequisitesValidationResults();
     $payment_module_id = modApiFunc("Checkout", "getChosenPaymentModuleIdCZ");
     $required_cc_info_prerequisite_name = Checkout::getAdditionalPrerequisiteName("creditCardInfo", $payment_module_id);
     $required_bank_account_info_prerequisite_name = Checkout::getAdditionalPrerequisiteName("bankAccountInfo", $payment_module_id);
     loadCoreFile('db_multiple_insert.php');
     $query = new DB_Multiple_Insert('order_person_data');
     $query->setInsertFields(array('order_id', 'person_info_variant_id', 'person_attribute_id', 'order_person_data_name', 'order_person_data_value', 'order_person_data_description', 'order_person_data_b_encrypted', 'order_person_data_encrypted_secret_key', 'order_person_data_rsa_public_key_asc_format'));
     foreach ($data as $prerequisite_key => $info) {
         if (_ml_strpos($prerequisite_key, "Module") || $prerequisite_key == 'subscriptionTopics') {
             //"shippingModuleAndMethod","paymentModule"
         } else {
             if (_ml_strpos($prerequisite_key, "creditCardInfo") !== FALSE) {
                 /**
                  * Define, if this creditCardInfo instance matches
                  * the selected payment module.
                  * If it does, then write it to the DB. Make two instances:
                  * 1. not encrypted obfuscaed one
                  * 2. not obfuscated encrypted one.
                  */
                 if ($prerequisite_key == $required_cc_info_prerequisite_name) {
                     /*
                       Ask the payment module, if it has to store Credit Card Info
                       in the database, or it won't be used after creating the order.
                     */
                     $mInfo = Checkout::getPaymentModuleInfo($payment_module_id);
                     $mmObj =& $application->getInstance('Modules_Manager');
                     $mmObj->includeAPIFileOnce($mInfo["APIClassName"]);
                     /* This condition can be checked only after loading */
                     if (is_callable(array($mInfo["APIClassName"], "storeCreditCardInfoInDB"))) {
                         $b_storeCreditCardInfoInDB = call_user_func(array($mInfo["APIClassName"], 'storeCreditCardInfoInDB'));
                         if ($b_storeCreditCardInfoInDB === true) {
                             $symmetric_secret_key = modApiFunc("Crypto", "blowfish_gen_blowfish_key");
                             $rsa_public_key = modApiFunc("Payment_Module_Offline_CC", "getRSAPublicKeyInCryptRSAFormat");
                             $rsa_public_key_asc_format = modApiFunc("Payment_Module_Offline_CC", "getRSAPublicKeyInASCFormat");
                             $rsa_obj = new Crypt_RSA();
                             $encrypted_symmetric_secret_key = $rsa_obj->encrypt($symmetric_secret_key, $rsa_public_key);
                             //Decrypt data in the session
                             $this->decrypt_prerequisite_with_checkout_cz_blowfish_key($prerequisite_key);
                             $decrypted_data = $this->getPrerequisitesValidationResults();
                             $info = $decrypted_data[$prerequisite_key];
                             //Encrypt data in the session
                             $this->encrypt_prerequisite_with_checkout_cz_blowfish_key($prerequisite_key);
                             $person_info_variant_id = $this->getPersonInfoVariantId($prerequisite_key, $info['variant_tag']);
                             //Encrypt data in the session
                             foreach ($info["validatedData"] as $attribute_key => $validatedData) {
                                 $attribute_id = $validatedData["id"];
                                 $attribute_visible_name = $validatedData["attribute_visible_name"];
                                 if ($attribute_key == "CreditCardType") {
                                     $cc_type_names = modApiFunc("Configuration", "getCreditCardSettings");
                                     $attribute_value = $cc_type_names[$validatedData["value"]]["name"];
                                 } else {
                                     $attribute_value = $validatedData["value"];
                                 }
                                 $attribute_description = $validatedData["attribute_description"];
                                 // add the not encrypted obfuscated value
                                 $b_encrypted = "0";
                                 $i_arr = array('order_id' => $order_id, 'person_info_variant_id' => $person_info_variant_id, 'person_attribute_id' => $attribute_id, 'order_person_data_name' => $attribute_visible_name, 'order_person_data_value' => $this->get_public_view_of_secured_data($attribute_value, $attribute_id), 'order_person_data_description' => $attribute_description, 'order_person_data_b_encrypted' => $b_encrypted, 'order_person_data_encrypted_secret_key' => $encrypted_symmetric_secret_key, 'order_person_data_rsa_public_key_asc_format' => $rsa_public_key_asc_format);
                                 $query->addInsertValuesArray($i_arr);
                                 // add the not obfuscated encrypted value
                                 $i_arr['order_person_data_b_encrypted'] = "1";
                                 $i_arr['order_person_data_value'] = base64_encode($this->encryptOrderPersonAttribute($attribute_value, $symmetric_secret_key));
                                 $query->addInsertValuesArray($i_arr);
                             }
                         }
                     }
                 }
             } else {
                 //                    ,                                                 ,
                 //                ,                                  ,
                 //                              .
                 if (_ml_strpos($prerequisite_key, "bankAccountInfo") !== FALSE && $required_bank_account_info_prerequisite_name != $prerequisite_key) {
                     //BankAccountInfo,
                 } else {
                     $person_info_variant_id = $this->getPersonInfoVariantId($prerequisite_key, $info['variant_tag']);
                     // add to the table order_person_data
                     foreach ($info["validatedData"] as $attribute_key => $validatedData) {
                         if ($attribute_key == "Statemenu" || $attribute_key == "Statetext") {
                             //An attribute "state" from the DB matches two attributes
                             // state_menu and state_text in the session. They are mutually exclussive in meaning:
                             // state_menu is the ID of the record about the state in the DB, i.e.
                             // a number. sate_text is a state name, inputted manually by a customer.
                             // It is inputted only if the customer selected a country, which has no
                             // defined states in the DB. As for now (Dec 2005) in the DB
                             // in the field "state" is saved only one of the values, which is not empty.
                             // Either sate_menu, or state_text.
                             if ($attribute_key == "Statetext") {
                                 continue;
                             }
                             if ($attribute_key == "Statemenu") {
                                 $state_menu_value = $info["validatedData"]["Statemenu"]["value"];
                                 $state_text_value = $info["validatedData"]["Statetext"]["value"];
                                 //FIMXE: check if both values are empty.
                                 $value = empty($state_menu_value) ? $state_text_value : $state_menu_value;
                                 //: analyze the conversion "1 atribute" <=> "2 attributes" for
                                 // "state". As for now(Dec 2005) data on DB-attribute "state"
                                 // is saved to the session-attribute "Statemenu"
                                 //Write a state name, but not the id
                                 //: depends on another attribute value: Country
                                 if (is_numeric($value)) {
                                     //: can validatedData contain a nested
                                     //  structure with the same name validatedData?
                                     $states = modApiFunc("Location", "getStates", $info["validatedData"]["Country"]["value"]);
                                     $value = $states[$value];
                                 }
                                 // add to the table order_person_data
                                 $i_arr = array('order_id' => $order_id, 'person_info_variant_id' => $person_info_variant_id, 'person_attribute_id' => $validatedData["id"], 'order_person_data_name' => $validatedData["attribute_visible_name"], 'order_person_data_value' => $value, 'order_person_data_description' => $validatedData["attribute_description"], 'order_person_data_b_encrypted' => "0", 'order_person_data_encrypted_secret_key' => "", 'order_person_data_rsa_public_key_asc_format' => "");
                                 $query->addInsertValuesArray($i_arr);
                             }
                         } else {
                             //Write a name for the country rather than the id
                             if ($attribute_key == "Country") {
                                 $countries = modApiFunc("Location", "getCountries");
                                 $value = empty($validatedData["value"]) ? "" : $countries[$validatedData["value"]];
                             } else {
                                 $value = $validatedData["value"];
                             }
                             $i_arr = array('order_id' => $order_id, 'person_info_variant_id' => $person_info_variant_id, 'person_attribute_id' => $validatedData["id"], 'order_person_data_name' => $validatedData["attribute_visible_name"], 'order_person_data_value' => $value, 'order_person_data_description' => $validatedData["attribute_description"], 'order_person_data_b_encrypted' => "0", 'order_person_data_encrypted_secret_key' => "", 'order_person_data_rsa_public_key_asc_format' => "");
                             $query->addInsertValuesArray($i_arr);
                         }
                     }
                 }
             }
         }
     }
     $application->db->PrepareSQL($query);
     return $application->db->DB_Exec();
 }
示例#27
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())));
     }
 }
示例#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;
 }
示例#29
0
function tk_encrypt($key, $crypt_data)
{
    if (function_exists('openssl_private_encrypt') == TRUE) {
        openssl_private_encrypt($crypt_data, $encrypted_data, $key, OPENSSL_PKCS1_PADDING);
    } else {
        require_once 'RSA.php';
        $rsa = new Crypt_RSA();
        $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
        $rsa->loadKey($key);
        $encrypted_data = $rsa->encrypt($crypt_data);
    }
    return $encrypted_data;
}
 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));
 }