Example #1
0
function prevChar($c)
{
    $car = bin2hex($c);
    $car = hexdec($car) - 1;
    $car = dechex($car);
    return hex2bin($car);
}
Example #2
0
function get_replay_type($data, $fileExtension)
{
    if (strcasecmp($fileExtension, "cnc4replay") == 0) {
        return "cnc4replay";
    }
    if (strcasecmp($fileExtension, "ra3replay") == 0) {
        return "ra3replay";
    }
    if (strcasecmp($fileExtension, "kwreplay") == 0) {
        return "kwreplay";
    }
    if (strcasecmp($fileExtension, "cnc3replay") == 0) {
        return "cnc3replay";
    }
    if (strcasecmp($fileExtension, "rep") == 0) {
        return "rep";
    }
    if (strcasecmp($fileExtension, "rec") == 0) {
        $hexdata = bin2hex($data);
        //先判断是否英雄连,第五个字节后为coh
        $cohToken = substr($hexdata, 8, 6);
        $cohToken = hex2bin($cohToken);
        if ($cohToken == "COH") {
            return "rec";
        }
        //是英雄连
        $dowToken = substr($hexdata, 24, 8);
        $dowToken = hex2bin($dowToken);
        if ($dowToken == "DOW2") {
            return "dow2";
        }
    }
}
Example #3
0
 public function testCompatibility()
 {
     $h = hex2bin('cfceb8891c58071deedbd1');
     $k = 'key123';
     $p = 'hello world';
     $this->assertEquals($p, Otp::crypt($h, $k));
 }
Example #4
0
function mta_decode($headers, $data)
{
    $encode_types = get_content_encoding($headers);
    $types = explode(',', $encode_types);
    $res_data = $data;
    foreach ($types as $type) {
        if ($type == 'rc4') {
            $res_data = mta_rc4($res_data);
        } else {
            if ($type == 'gzip') {
                $header = unpack('Nlength/Lgzip', $res_data);
                if (intval($header['gzip']) === 0x88b1f) {
                    $header = unpack('Nlength/H*body', $res_data);
                    //$header['ori_buf'] = bin2hex($res_data);
                    //$header['ori_len'] = strlen($res_data);
                    $res_data = hex2bin($header['body']);
                } else {
                }
                $res_data = gzdecode($res_data);
                //jsondb_logger('nofity', 'gzip log', ['res'=>$res_data,'len'=>strlen($res_data),'header'=>$header]);
            }
        }
    }
    if (empty($res_data)) {
        jsondb_logger('notify', 'error ' . bin2hex($data));
    }
    return json_decode($res_data);
}
 /**
  * Decrypt the given value.
  *
  * @param string $value
  * 
  * @return string
  */
 private function decrypt($value)
 {
     if ($this->cipher) {
         return $this->cipher->decrypt(hex2bin($value));
     }
     return $value;
 }
Example #6
0
 public function testOurSubstrTrailingEmptyStringBugWeird()
 {
     $str = hex2bin('4d8ab774261977e13049c42b4996f2c4');
     $this->assertSame(16, Core::ourStrlen($str));
     if (ini_get('mbstring.func_overload') == 7) {
         // This checks that the above hex string is indeed "weird."
         // Edit: Er... at least, on PHP 5.6.0 and above it's weird.
         //  I DON'T KNOW WHY THE LENGTH OF A STRING DEPENDS ON THE VERSION
         //  OF PHP BUT APPARENTLY IT DOES ¯\_(ツ)_/¯
         if (version_compare(phpversion(), '5.6.0', '>=')) {
             $this->assertSame(12, strlen($str));
         } else {
             $this->assertSame(16, strlen($str));
         }
     } else {
         $this->assertSame(16, strlen($str));
         // We want ourSubstr to behave identically to substr() in PHP 7 in
         // the non-mbstring case. This double checks what that behavior is.
         if (version_compare(phpversion(), '7.0.0', '>=')) {
             $this->assertSame('', substr('ABC', 3, 0));
             $this->assertSame('', substr('ABC', 3));
         } else {
             // The behavior was changed for PHP 7. It used to be...
             $this->assertSame(false, substr('ABC', 3, 0));
             $this->assertSame(false, substr('ABC', 3));
         }
         // Seriously, f**k this shit. Don't use PHP. ╯‵Д′)╯彡┻━┻
     }
     // This checks that the behavior is indeed the same.
     $this->assertSame('', Core::ourSubstr($str, 16));
 }
Example #7
0
function tagrm_post(&$a)
{
    if (!local_user()) {
        goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
    }
    if (x($_POST, 'submit') && $_POST['submit'] === t('Cancel')) {
        goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
    }
    $tag = x($_POST, 'tag') ? hex2bin(notags(trim($_POST['tag']))) : '';
    $item = x($_POST, 'item') ? intval($_POST['item']) : 0;
    $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($item), intval(local_user()));
    if (!count($r)) {
        goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
    }
    $arr = explode(',', $r[0]['tag']);
    for ($x = 0; $x < count($arr); $x++) {
        if ($arr[$x] === $tag) {
            unset($arr[$x]);
            break;
        }
    }
    $tag_str = implode(',', $arr);
    q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d AND `uid` = %d LIMIT 1", dbesc($tag_str), intval($item), intval(local_user()));
    info(t('Tag removed') . EOL);
    goaway($a->get_baseurl() . '/' . $_SESSION['photo_return']);
    // NOTREACHED
}
Example #8
0
 private function get_peers_blocking($info_hash, $host = "router.bittorrent.com", $port = 6881)
 {
     //create a UDP socket to send commands through
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     //Create Command Packet
     $packet = bencode::encode(array("id" => $this->get_unique_node_id(), "info_hash" => hex2bin($info_hash)), array("q" => "get_peers", "t" => $this->unique_id(), "y" => "q"));
     socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);
     //set timeout
     $timeout = array('sec' => 5, 'usec' => 0);
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
     $time = time();
     //recieve data
     try {
         socket_recvfrom($socket, $buf, 12000, 0, $host, $port);
     } catch (Exception $e) {
         echo "Error";
         return FALSE;
     }
     //have to manually do the timeout, cant seem to get info from this socket
     if (time() - $time >= 4) {
         socket_close($socket);
         return FALSE;
     }
     //close socket so bad shit don't happen
     socket_close($socket);
     return nodeExtract::return_nodes(bencode::decode($buf));
 }
Example #9
0
 /**
  * Hex to bin.
  *
  * @param string $value hex string
  * @return string
  */
 public static function hexToBin($value)
 {
     if (function_exists('hex2bin')) {
         return hex2bin($value);
     }
     return pack("H*", $value);
 }
Example #10
0
 /**
  * @covers \Sarciszewski\PHPFuture\Security::pbkdf2()
  * ref https://www.ietf.org/rfc/rfc6070.txt
  */
 public function testPBKDF2()
 {
     $a = Future\Security::pbkdf2("sha1", "password", "salt", 2, 20, true);
     $this->assertEquals($a, hex2bin('ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957'));
     $b = Future\Security::pbkdf2("sha1", "password", "salt", 2, 20, false);
     $this->assertEquals($b, 'ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957');
 }
Example #11
0
 /**
  * Custom implementation of hex2bin since the function is only available starting
  * with PHP 5.4
  *
  * @TODO Remove this once 5.3 support for ownCloud is dropped
  * @param $message
  * @return string
  */
 protected static function hexToBin($message)
 {
     if (function_exists('hex2bin')) {
         return hex2bin($message);
     }
     return pack("H*", $message);
 }
Example #12
0
/**
 * decode_password - decode encoded password to ascii string
 * @RA: Request Authenticator passed in from the Access Point
 * @encoded: The encoded password
 * @secret: Shared secret between node and server
 *
 * Returns decoded password or FALSE on error
 */
function decode_password($RA, $encoded, $secret)
{
    if (strlen($RA) != 32) {
        return FALSE;
    }
    $ra = hex2bin($RA);
    if ($ra === FALSE) {
        return FALSE;
    }
    if (strlen($encoded) % 32 != 0) {
        return FALSE;
    }
    $bincoded = hex2bin($encoded);
    $password = "";
    $last_result = $ra;
    for ($i = 0; $i < strlen($bincoded); $i += 16) {
        $key = hash('md5', $secret . $last_result, TRUE);
        for ($j = 0; $j < 16; $j++) {
            $password .= $key[$j] ^ $bincoded[$i + $j];
        }
        $last_result = substr($bincoded, $i, 16);
    }
    $j = 0;
    for ($i = strlen($password); $i > 0; $i--) {
        if ($password[$i - 1] != "") {
            break;
        } else {
            $j++;
        }
    }
    if ($j > 0) {
        $password = substr($password, 0, strlen($password) - $j);
    }
    return $password;
}
 public function downloadAction($name = null)
 {
     $this->load->helper('download');
     $name = hex2bin($name);
     $array = $this->_get($name, true);
     force_download($name . '.php', $array, true);
 }
Example #14
0
function decryptPassword($input)
{
    $config = $GLOBALS['config'];
    if ($config['rsa_modulus'] != '' && $config['rsa_exponent'] != '' && $config['rsa_key'] != '' && isset($_SESSION['crypt_key'])) {
        if (substr($input, 0, 5) == "enc: ") {
            $input = substr($input, 5);
            $res = openssl_pkey_get_private($config['rsa_key'], $config['rsa_passphrase']);
            openssl_private_decrypt(hex2bin($input), $plaintext, $res);
            $plaintext = utf8_encode($plaintext);
            //loop through current session login keys and try all of them that haven't expired
            foreach ($_SESSION['crypt_key'] as $arrayKey => $key_array) {
                //key_array is array(time key was generated, hexadecimal key)
                if (time() - $key_array[0] > 5 * 60) {
                    //delete keys older than 5 minutes
                    //shouldn't take that long to login anyway!
                    unset($_SESSION['crypt_key'][$arrayKey]);
                } else {
                    $crypt_key = $key_array[1];
                    //first part of plaintext should be equal to crypt key
                    if (substr($plaintext, 0, strlen($crypt_key)) == $crypt_key) {
                        return substr($plaintext, strlen($crypt_key));
                    }
                }
            }
            //none of the keys above worked, either forgery or expired form
            return "";
        } else {
            return $input;
        }
    } else {
        return $input;
    }
}
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->prepareExecute($input, $output, $this);
     $this->connectMultichain();
     $this->multichainDebug($output);
     $this->connectMysql();
     $documentPath = $input->getArgument("document");
     $content = file_get_contents($documentPath);
     $hash = hash('sha256', $content);
     /** @var Document $ormDocument */
     $ormDocument = $this->em->getRepository('Multichain\\Console\\Entity\\Document')->findOneByContent($content);
     if ($ormDocument) {
         $hex = $ormDocument->getHex();
         $transaction = $this->multichain->getRawTransaction($hex, 1);
         $data = $transaction["data"][0];
         $parsedData = json_decode(hex2bin($data), true);
         $originalHash = $parsedData["hash"];
         $this->io->text("Submitted document has a hash of <fg=blue>" . $hash . "</fg=blue>");
         $this->io->text("Found document the same content in the MySQL database");
         if ($hash == $originalHash) {
             $this->io->text("Validated the hash found in the database with the Blockchain");
             $this->io->success('Hashes match! ' . $documentPath . ' is validated by the Blockchain');
         } else {
             $this->io->text("Unable to validated the hash found in the database with the Blockchain");
             $this->io->error('Hashes do not match! ' . $documentPath . ' is NOT validated by the Blockchain');
         }
     } else {
         $this->io->text("Submitted document has a hash of <fg=blue>" . $hash . "</fg=blue>");
         $this->io->text("Found no document with the same content.");
         $this->io->error('Hashes do not match! ' . $documentPath . ' is NOT validated by the Blockchain');
     }
 }
 public function testUnpacking()
 {
     $request = EndRequest::unpack(hex2bin(self::$rawMessage));
     $this->assertEquals(FCGI::END_REQUEST, $request->getType());
     $this->assertEquals(FCGI::REQUEST_COMPLETE, $request->getProtocolStatus());
     $this->assertEquals(100, $request->getAppStatus());
 }
Example #17
0
 public function testCoordsToWkbShouldReturnTheCorrectHexString()
 {
     $lat = -2.714586;
     $lng = 15.419785;
     $expected = hex2bin('000000000101000000876F61DD78B705C0E5B33C0FEED62E40');
     $this->assertEquals($expected, Utils::coordsToWkb($lat, $lng));
 }
Example #18
0
 function display($tpl = null)
 {
     $game_id = bin2hex(JRequest::getVar('game_id'));
     $greeting = "Hola mundo Games" . hex2bin($game_id);
     $this->assignRef('greeting', $greeting);
     parent::display($tpl);
 }
Example #19
0
function encode_password($plain, $challenge, $secret)
{
    if (strlen($challenge) % 2 != 0 || strlen($challenge) == 0) {
        return FALSE;
    }
    $hexchall = hex2bin($challenge);
    if ($hexchall === FALSE) {
        return FALSE;
    }
    if (strlen($secret) > 0) {
        $crypt_secret = md5($hexchall . $secret, TRUE);
        $len_secret = 16;
    } else {
        $crypt_secret = $hexchall;
        $len_secret = strlen($hexchall);
    }
    /* simulate C style \0 terminated string */
    $plain .= "";
    $crypted = '';
    for ($i = 0; $i < strlen($plain); $i++) {
        $crypted .= $plain[$i] ^ $crypt_secret[$i % $len_secret];
    }
    $extra_bytes = 0;
    //rand(0, 16);
    for ($i = 0; $i < $extra_bytes; $i++) {
        $crypted .= chr(rand(0, 255));
    }
    return bin2hex($crypted);
}
Example #20
0
 /**
  * 验签
  *
  * @param string $data
  * @param string $sign
  * @param string $pem
  * @return bool 验签状态
  */
 private function verify($data, $sign)
 {
     $p = openssl_pkey_get_public(file_get_contents($this->chinaums_config['publickKey']));
     $verify = openssl_verify($data, hex2bin($sign), $p);
     openssl_free_key($p);
     return $verify > 0;
 }
 public function decode()
 {
     $this->channel = $this->getString();
     switch ($this->channel) {
         case "REGISTER":
             $channels = bin2hex($this->getString());
             $channels = str_split($channels, 2);
             $string = "";
             foreach ($channels as $num => $str) {
                 if ($str === "00") {
                     $this->data[] = hex2bin($string);
                     $string = "";
                 } else {
                     $string .= $str;
                     if (count($channels) - 1 === $num) {
                         $this->data[] = hex2bin($string);
                     }
                 }
             }
             break;
         case "MC|Brand":
             $this->data = $this->getString();
             break;
     }
 }
Example #22
0
 public function testHexToBinInvalid()
 {
     $this->assertNull(@hex2bin(array()));
     // Invalid type
     $this->assertFalse(@hex2bin("123"));
     // Invalid string length
 }
Example #23
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  Request  $request
  * @return Response
  */
 public function store(Request $request)
 {
     //
     //Log::info('$request=<' . $request . '>');
     if ($request->isMethod('post')) {
         $bodyContent = $request->getContent();
         //Log::info('$bodyContent=<' . $bodyContent . '>');
         $bodyJson = json_decode($bodyContent);
         $keyPath = $this->keyRoot_ . $bodyJson->token . '/pubKey.pem';
         $fp = fopen($keyPath, 'r');
         $pubKeyMem = fread($fp, 8192);
         fclose($fp);
         $pubkeyid = openssl_pkey_get_public($pubKeyMem);
         $token = $bodyJson->token;
         $sign = $bodyJson->sign;
         $ok = openssl_verify($token, hex2bin($sign), $pubkeyid, "sha256");
         openssl_free_key($pubkeyid);
         if ($ok == 1) {
             $profilePath = $this->keyRoot_ . $bodyJson->token . '/profile';
             //Log::info('$bodyJson->payload=<' . json_encode($bodyJson->payload) . '>');
             file_put_contents($profilePath, json_encode($bodyJson->payload));
             return response()->json(['status' => 'success']);
         } else {
             return response()->json(['status' => 'failure']);
         }
     }
 }
Example #24
0
 function get()
 {
     if (!local_channel()) {
         goaway(z_root() . '/' . $_SESSION['photo_return']);
         // NOTREACHED
     }
     // remove tag on the fly if item and tag are provided
     if (argc() == 4 && argv(1) === 'drop' && intval(argv(2))) {
         $item = intval(argv(2));
         $tag = argv(3);
         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($item), intval(local_channel()));
         if (!$r) {
             goaway(z_root() . '/' . $_SESSION['photo_return']);
         }
         $r = fetch_post_tags($r, true);
         $item = $r[0];
         $new_tags = array();
         if ($item['term']) {
             for ($x = 0; $x < count($item['term']); $x++) {
                 if ($item['term'][$x]['term'] !== hex2bin($tag)) {
                     $new_tags[] = $item['term'][$x];
                 }
             }
         }
         if ($new_tags) {
             $item['term'] = $new_tags;
         } else {
             unset($item['term']);
         }
         item_store_update($item);
         info(t('Tag removed') . EOL);
         goaway(z_root() . '/' . $_SESSION['photo_return']);
     }
     //if we got only the item print a list of tags to select
     if (argc() == 3 && argv(1) === 'drop' && intval(argv(2))) {
         $o = '';
         $item = intval(argv(2));
         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", intval($item), intval(local_channel()));
         if (!$r) {
             goaway(z_root() . '/' . $_SESSION['photo_return']);
         }
         $r = fetch_post_tags($r, true);
         if (!count($r[0]['term'])) {
             goaway(z_root() . '/' . $_SESSION['photo_return']);
         }
         $o .= '<h3>' . t('Remove Item Tag') . '</h3>';
         $o .= '<p id="tag-remove-desc">' . t('Select a tag to remove: ') . '</p>';
         $o .= '<form id="tagrm" action="tagrm" method="post" >';
         $o .= '<input type="hidden" name="item" value="' . $item . '" />';
         $o .= '<ul>';
         foreach ($r[0]['term'] as $x) {
             $o .= '<li><input type="checkbox" name="tag" value="' . bin2hex($x['term']) . '" >' . bbcode($x['term']) . '</input></li>';
         }
         $o .= '</ul>';
         $o .= '<input id="tagrm-submit" type="submit" name="submit" value="' . t('Remove') . '" />';
         $o .= '<input id="tagrm-cancel" type="submit" name="submit" value="' . t('Cancel') . '" />';
         $o .= '</form>';
         return $o;
     }
 }
Example #25
0
 /**
  * @expectedException \Defuse\Crypto\Exception\InvalidCiphertext
  */
 public function testBitflip()
 {
     $key = \Defuse\Crypto\Key::LoadFromAsciiSafeString(\hex2bin('0102030405060708090a0b0c0d0e0f10'));
     $password = PasswordLock::hashAndEncrypt('YELLOW SUBMARINE', $key);
     $password[0] = \ord($password[0]) === 0 ? 255 : 0;
     PasswordLock::decryptAndVerify('YELLOW SUBMARINE', $password, $key);
 }
 /**
  * Composes message to binary data to send it via stream
  *
  * @param SocketMessage $socketMessage
  *
  * @return string
  *
  */
 public function compose(SocketMessage $socketMessage)
 {
     //Correlation + flag length + command length
     $messageLength = MessageConfiguration::HEADER_LENGTH;
     $doAuthorization = $socketMessage->getCredentials() ? true : false;
     $authorizationLength = 0;
     if ($doAuthorization) {
         $authorizationLength = 1 + strlen($socketMessage->getCredentials()->getUsername()) + 1 + strlen($socketMessage->getCredentials()->getPassword());
     }
     $dataToSend = $socketMessage->getData();
     if ($dataToSend) {
         $dataToSend = $dataToSend->serializeToString();
         $messageLength += strlen($dataToSend);
     }
     $wholeMessageLength = $messageLength + $authorizationLength + MessageConfiguration::INT_32_LENGTH;
     $buffer = new Buffer($wholeMessageLength);
     $buffer->writeInt32LE($messageLength + $authorizationLength, 0);
     $buffer->writeInt8($socketMessage->getMessageType()->getType(), MessageConfiguration::MESSAGE_TYPE_OFFSET);
     $buffer->writeInt8($doAuthorization ? MessageConfiguration::FLAG_AUTHORIZATION : MessageConfiguration::FLAGS_NONE, MessageConfiguration::FLAG_OFFSET);
     $buffer->write(hex2bin($this->createCorrelationID($socketMessage->getCorrelationID())), MessageConfiguration::CORRELATION_ID_OFFSET);
     if ($doAuthorization) {
         $usernameLength = strlen($socketMessage->getCredentials()->getUsername());
         $passwordLength = strlen($socketMessage->getCredentials()->getPassword());
         $buffer->writeInt8($usernameLength, MessageConfiguration::DATA_OFFSET);
         $buffer->write($socketMessage->getCredentials()->getUsername(), MessageConfiguration::DATA_OFFSET + 1);
         $buffer->writeInt8($passwordLength, MessageConfiguration::DATA_OFFSET + 1 + $usernameLength);
         $buffer->write($socketMessage->getCredentials()->getPassword(), MessageConfiguration::DATA_OFFSET + 1 + $usernameLength + 1);
     }
     if ($dataToSend) {
         $buffer->write($dataToSend, MessageConfiguration::DATA_OFFSET + $authorizationLength);
     }
     return (string) $buffer;
 }
Example #27
0
function dnpt($ext_ip, $ext_prefix, $int_prefix)
{
    $debug = false;
    // This is not a complete solution!!!!!!!!!!!!!!!!!!!!!!!!!!
    $ext_prefix = str_replace(":", "", $ext_prefix);
    $int_prefix = str_replace(":", "", $int_prefix);
    // hehe
    $sauce = hexdec(split(":", $ext_ip)[4]);
    $ext_c = icmpChecksum(hex2bin($ext_prefix));
    $int_c = icmpChecksum(hex2bin($int_prefix));
    if ($debug) {
        print_r(unpack('n', $int_c));
    }
    $diff = unpack('n', $ext_c)[1] - unpack('n', $int_c)[1];
    if ($diff < 0) {
        $diff = 0xffff + $diff;
    }
    $diff = $sauce - $diff;
    if ($debug) {
        print bin2hex($ext_c);
        print "\n";
        print bin2hex($int_c);
        print "\n";
        print dechex($diff);
        print "\n";
    }
    $out = split(":", $ext_ip);
    $out[4] = dechex($diff);
    $out = join($out, ":");
    return $out;
}
Example #28
0
 private function disassembleId($id)
 {
     $vars = unpack('Nts/C3m/vpid/C3i', hex2bin($id));
     $this->timestamp = $vars['ts'];
     $this->pid = $vars['pid'];
     $this->inc = $vars['i3'] | $vars['i2'] << 8 | $vars['i1'] << 16;
 }
Example #29
0
 public function testHex2binThree()
 {
     $data = "וּמִפְּרִ֣י הָעֵץ֮ אֲשֶׁ֣ר בְּתוֹךְ־הַגָּן֒ אָמַ֣ר אֱלֹהִ֗ים לֹ֤א תֹֽאכְלוּ֙ מִמֶּ֔נּוּ וְלֹ֥א תִגְּע֖וּ בּ֑וֹ פֶּן־תְּמֻתֽוּן׃ ";
     $hex = bin2hex($data);
     $this->assertEquals($data, hex2bin($hex));
     $this->assertEquals($data, Filter_Hex::hex2bin($hex));
 }
Example #30
0
 /**
  * @dataProvider providerRead
  *
  * @param string  $ewkb       The EWKB to read, hex-encoded.
  * @param string  $ewkt       The expected EWKT output.
  */
 public function testRead($ewkb, $ewkt)
 {
     $reader = new EWKBReader();
     $writer = new EWKTWriter();
     $geometry = $reader->read(hex2bin($ewkb));
     $this->assertSame($ewkt, $writer->write($geometry));
 }