Sunday, December 23, 2018

basic encruption example

<!DOCTYPE html>
<html>
<title>basic encruption example</title>


<head>


<?php
// DEFINE our cipher
define('AES_256_CBC', 'aes-256-cbc');

// Generate a 256-bit encryption key
// This should be stored somewhere instead of recreating it each time

$encryption_key = openssl_random_pseudo_bytes(32);

// Generate an initialization vector
// This *MUST* be available for decryption as well

$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC));

// Create some data to encrypt

$data =  $_POST['key'];;
echo "Before encryption: $data\n";
echo "<br>";

// Encrypt $data using aes-256-cbc cipher with the given encryption key and
// our initialization vector. The 0 gives us the default options, but can
// be changed to OPENSSL_RAW_DATA or OPENSSL_ZERO_PADDING

$encrypted = openssl_encrypt($data, AES_256_CBC, $encryption_key, 0, $iv);

echo "Encrypted: $encrypted\n"; echo "<br>";

// If we lose the $iv variable, we can't decrypt this, so:
// - $encrypted is already base64-encoded from openssl_encrypt
// - Append a separator that we know won't exist in base64, ":"

// - And then append a base64-encoded $iv

$encrypted = $encrypted . ':' . base64_encode($iv);

// To decrypt, separate the encrypted data from the initialization vector ($iv).

$parts = explode(':', $encrypted);

// $parts[0] = encrypted data
// $parts[1] = base-64 encoded initialization vector
// Don't forget to base64-decode the $iv before feeding it back to
//openssl_decrypt

$decrypted = openssl_decrypt($parts[0], AES_256_CBC, $encryption_key, 0, base64_decode($parts[1]));

echo "Decrypted: $decrypted\n";
?>


<?php
/*
print("-- Start --<br />");

$z = $_POST['key'];
$data = $_POST['plaintext'];
$mode = $_POST['mode'];
$iv = $_POST['iv'];

include("AES.class.php");

$aes = new AES($z, $mode, $iv);
$starte = microtime(true);
$encrypted = $aes->encrypt($data);
$ende = microtime(true);
print "Execution time to encrypt: " . ($ende - $starte) . " seconds<br />";
print "Cipher-Text: " . $encrypted . "<br />";
print "Hex: " . bin2hex($encrypted) . "<br />";
print "Base 64: " . base64_encode($encrypted) . "<br /><br />";
$startd = microtime(true);
$decrypted = $aes->decrypt($encrypted);
$endd = microtime(true);
print "Execution time to decrypt: " . ($endd - $startd) . " seconds<br />";
print "Decrypted-Text: " . stripslashes($decrypted);
print "<br />-- End --<br />";

*/
?>
</head>





<body>

<form method="POST" action="">
  <table>
    <tr><td align="right">Key:</td><td><input type="text" name="key" value="" size="34">
</td></tr>
    <tr><td align="right">Mode:</td><td>
<select name="mode" style="width: 120px">
<option value="ECB">ECB</option><option value="CBC" selected>CBC</option>
<option value="CFB">CFB</option>
<option value="OFB">OFB</option>
</select></td></tr>
    <tr><td align="right">Initialization Vector:</td><td>



<input type="text" name="iv" value="" size="16"> (used in all modes except ECB)</td></tr>
    <tr><td align="right" valign="top">Plain-Text:</td><td>
<textarea name="plaintext" cols="40" rows="5"></textarea></td></tr>
    <tr><td></td><td><input type="submit" name="submit" value="Encrypt!"></td></tr></p>
  </table>
  </form>




</body>
</html>





<?php
$data 
"hello";

foreach (
hash_algos() as $v) {
        
$r hash($v$datafalse);
        
printf("%-12s %3d %s\n"$vstrlen($r), $r);
?> 



<?php
  
echo "Building data...";
  
$data "";
  for(
$i 0$i 1500$i++)
    
$data .= sha1("H:k - $i - k:H");

  echo 
"OK! (".strlen($data)." bytes)".PHP_EOL;

  
$res = [];

  echo 
"Testing hashes.....".PHP_EOL;

  foreach (
hash_algos() as $algo) {
    
$time microtime(1);
    
$hash hash($algo$data);
    
$time = (microtime(1) - $time) * 1000;
    
$length strlen($hash);

    
$res["$time"][] = [
      
"algo"   => "HEX-$algo",
      
"length" => "$length",
      
"time"   => sprintf("%.8f"$time)
    ];

    
$time microtime(1);
    
hash($algo$data1);
    
$time = (microtime(1) - $time) * 1000;

    
$res["$time"][] = [
      
"algo"   => "RAW-$algo",
      
"length" => "$length",
      
"time"   => sprintf("%.8f"$time)
    ];
  }

  
ksort($res);
  
$i 0;

  echo 
"Results:".PHP_EOL;
  echo 
"Posit.      Time in ms   Type-Hash algo        Hash length".PHP_EOL;

  foreach(
$res as $sres){
    foreach(
$sres as $result){
      echo 
sprintf("%5d. %12s ms    %-20s %-2d bytes"$i++, $result['time'], $result['algo'], $result['length']).PHP_EOL;
    }
  }
?>






<?php
$val 
'hello';var_dump(crc32($val) == ( '0x' hash('crc32b'$val) ) ); // bool(true)var_dump(crc32($val) == ( '0x' hash('crc32'$val) ) ); // bool(false)?>





<?php
$val 
'hello';$crc64 = ( '0x' hash('crc32'$val) . hash('crc32b'$val) ) );var_dump($crc64); // string(18) "0x3d6531193610a686"var_dump($crc64 0); // int(4423996193312384646)?>

Thursday, December 20, 2018

PHP - Sacar XSS

PHP - Sacar XSS

function RemoveXSS($val)
{

$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A &#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
    // ;? matches the ;, which is optional
    // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

    // &#x0040 @ search for the hex values
    $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i],
        $val); // with a ;
    // &#00064 @ 0{0,7} matches '0' zero to seven times
    $val = preg_replace('/(&#0{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
}

// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml',
    'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame',
    'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate',
    'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate',
    'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload',
    'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick',
    'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable',
    'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag',
    'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop',
    'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin',
    'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete',
    'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave',
    'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel',
    'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange',
    'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart',
    'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll',
    'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop',
    'onsubmit', 'onunload');
$ra = array_merge($ra1, $ra2);

$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
    $val_before = $val;
    for ($i = 0; $i < sizeof($ra); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                $pattern .= '|';
                $pattern .= '|(&#0{0,8}([9|10|13]);)';
                $pattern .= ')*';
            }
            $pattern .= $ra[$i][$j];
        }
        $pattern .= '/i';
        $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
        $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
        if ($val_before == $val) {
            // no replacements were made, so exit the loop
            $found = false;
        }
    }
}
 return $val;
}




function sacarXss($val) {
   $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
   $search = 'abcdefghijklmnopqrstuvwxyz';
   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   $search .= '1234567890!@#$%^&*()';
   $search .= '~`";:?+/={}[]-_|\'\\';
   for ($i = 0; $i < strlen($search); $i++) {
      $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
   }
   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
   $ra = array_merge($ra1, $ra2);
   $found = true;
   while ($found == true) {
      $val_before = $val;
      for ($i = 0; $i < sizeof($ra); $i++) {
         $pattern = '/';
         for ($j = 0; $j < strlen($ra[$i]); $j++) {
            if ($j > 0) {
               $pattern .= '(';
               $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
               $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
               $pattern .= ')?';
            }
            $pattern .= $ra[$i][$j];
         }
         $pattern .= '/i';
         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2);
         $val = preg_replace($pattern, $replacement, $val);
         if ($val_before == $val) {
            $found = false;
         }
      }
   }
  return $val;
}
echo sacarXss("testeando javascript:alert('hola');");






Php sacar tags

function sacarTags($str){
if(trim($str)!=''){
$str = ereg_replace("<([^>]+)>", "", $str);
return $str;
}else{
return $str;
}
}

Php sacar href

function sacarHref($str){
if(trim($str)!=''){
$str = eregi_replace("<a([^>]+)>|</a>", "", $str);
return $str;
}else{
return $str;
}
}



PHP - Sacar Parametro de "string tipo QS"

function keepqsSinParametro($parametro, $keepqs = ''){
if( empty($keepqs) ) global $keepqs;
$keepqs = urldecode($keepqs);
return preg_replace('/[\&\?]?'.$parametro.'=[^\&]*/','', $keepqs);
}

Php sacar espacios
function sacarEspacios($str,$porQue="_"){
return ereg_replace("([ ]+)",$porQue,$str);
}



General Solution for vulnerable to cross-site scripting (XSS) filter function can be:


function xss_cleaner($input_str) {
    $return_str = str_replace( array('<','>',"'",'"',')','('), array('&lt;','&gt;','&apos;','&#x22;','&#x29;','&#x28;'), $input_str );
    $return_str = str_ireplace( '%3Cscript', '', $return_str );
    return $return_str;
}


Saturday, December 15, 2018

php function public,private,protected

Class properties must be defined as public, private, or protected. If declared using var, the property will be defined as public.

<?php/**
 * Define MyClass
 */
class MyClass{
    public 
$public 'Public';
    protected 
$protected 'Protected';
    private 
$private 'Private';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}
$obj = new MyClass();
echo 
$obj->public// Worksecho $obj->protected// Fatal Errorecho $obj->private// Fatal Error$obj->printHello(); // Shows Public, Protected and Private


/**
 * Define MyClass2
 */
class MyClass2 extends MyClass{
    
// We can redeclare the public and protected properties, but not private
    
public $public 'Public2';
    protected 
$protected 'Protected2';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}
$obj2 = new MyClass2();
echo 
$obj2->public// Worksecho $obj2->protected// Fatal Errorecho $obj2->private// Undefined$obj2->printHello(); // Shows Public2, Protected2, Undefined
?>

  • public scope to make that variable/function available from anywhere, other classes and instances of the object.
  • private scope when you want your variable/function to be visible in its own class only.
  • protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

Public:

When you declare a method (function) or a property (variable) as public, those methods and properties can be accessed by:
  • The same class that declared it.
  • The classes that inherit the above declared class.
  • Any foreign elements outside this class can also access those things.
Example:
<?php

class GrandPa
{
    public $name='kamran';  // A public variable
}

class Daddy extends GrandPa // Inherited class
{
    function displayGrandPaName()
    {
        return $this->name; // The public variable will be available to the inherited class
    }

}

// Inherited class Daddy wants to know Grandpas Name
$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'kamran'

// Public variables can also be accessed outside of the class!
$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Prints 'kamran'

Protected:

When you declare a method (function) or a property (variable) as protected, those methods and properties can be accessed by
  • The same class that declared it.
  • The classes that inherit the above declared class.
Outsider members cannot access those variables. "Outsiders" in the sense that they are not object instances of the declared class itself.
Example:
<?php

class GrandPa
{
    protected $name = 'kamran';
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }

}

$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Prints 'kamran'

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error
The exact error will be this:
PHP Fatal error: Cannot access protected property GrandPa::$name

Private:

When you declare a method (function) or a property (variable) as private, those methods and properties can be accessed by:
  • The same class that declared it.
Outsider members cannot access those variables. Outsiders in the sense that they are not object instances of the declared class itself and even the classes that inherit the declared class.
Example:
<?php

class GrandPa
{
    private $name = 'irfan';
}

class Daddy extends GrandPa
{
    function displayGrandPaName()
    {
        return $this->name;
    }

}

$daddy = new Daddy;
echo $daddy->displayGrandPaName(); // Results in a Notice 

$outsiderWantstoKnowGrandpasName = new GrandPa;
echo $outsiderWantstoKnowGrandpasName->name; // Results in a Fatal Error
The exact error messages will be:

form validation

function formsubmit ( ) { var empname = document .getElementById ( 'emp_name' ). value ; var email = document .getElem...