Thursday, December 30, 2010

Calculate sha1 thumbprint of ssl certificate

<?php
function sha1_thumbprint_pem($pem_file_contents)
{
    $file $pem_file_contents;
    $file preg_replace('/\-+BEGIN CERTIFICATE\-+/','',$file);
    $file preg_replace('/\-+END CERTIFICATE\-+/','',$file);
    $file trim($file);
    $file str_replacearray("\n\r","\n","\r"), ''$file);
    $bin base64_decode($file);
    return sha1($bin);
}
?>

Tuesday, December 14, 2010

preg_replace/preg_match utf8

preg_replace('/([^a-z\x{00C0}-\x{02AF}\x{0380}-\x{FFFF}\.\, ]|[\.\,][\.\,]+)/iu', '', $str);//allows most utf8

Friday, October 15, 2010

How to show the list of CA Root Certificates in Google Chrome in Ubuntu Linux

sudo apt-get install libnss3-tools
certutil -d sql:$HOME/.pki/nssdb -L -h "Builtin Object Token"

Monday, September 27, 2010

PHP CURLOPT_CERTINFO

sample php code using CURLOPT_CERTINFO, the php equivalent of CURLINFO_CERTINFO which is only available in php >=5.3.2 .
<?php
if($fp = tmpfile())
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,"https://www.digicert.com/");
    curl_setopt($ch, CURLOPT_STDERR, $fp);
    curl_setopt($ch, CURLOPT_CERTINFO, 1);//certinfo goes to STDERR when CURLOPT_VERBOSE is set
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
    curl_setopt($ch, CURLOPT_SSLVERSION,3);
    $result = curl_exec($ch);
    curl_errno($ch)==0 or die("Error:" . curl_errno($ch) . " Message:" . curl_error($ch));
    fseek($fp, 0);//rewind
    $str='';
    while(strlen($str.=fread($fp,8192))==8192);
    echo $str;
    fclose($fp);
}
?>

Wednesday, August 25, 2010

nice sanitized mysql insert sample php

$row = array();
$row["firstname"]="Billy";
$row["lastname"]="O'Leary";
$row["create_date"]=date("Y-m-d H:i:s");
$row["status"]="1";
$escaped = array_map(create_function('$a', 'return is_null($a) ? NULL : mysql_real_escape_string($a);'),$row);
$quoted = array_map(create_function('$a', 'return is_null($a) ? "NULL" : "\x27".$a."\x27";'),$escaped);
echo "INSERT INTO `employees`(`".implode("`,`",array_keys($escaped))."`) VALUES(".implode(",",array_values($quoted)).");"."\n";

it generates the sanitized insert query
INSERT INTO `employees`(`firstname`,`lastname`,`create_date`,`status`) VALUES('Billy','O\'Leary','2010-08-25 15:32:37','1');

Sunday, July 18, 2010

sed strip unicode out of file

e2 80 8b is the hex utf8 for unicode code point U+200b
sed -e "s/\xe2\x80\x8b//g" input.u8 >output.u8

Tuesday, July 13, 2010

mysql union

mysql> (select 'a') union (select 'a');
+---+
| a |
+---+
| a |
+---+
1 row in set (0.00 sec)

mysql> (select 'a') union all (select 'a');
+---+
| a |
+---+
| a |
| a |
+---+
2 rows in set (0.00 sec)

mysql> (select 'a') union distinct (select 'a');
+---+
| a |
+---+
| a |
+---+
1 rows in set (0.00 sec)

Wednesday, June 30, 2010

maximum upload size in php


<?php
function max_upload_size()
{
    preg_match('/^([0-9]+)([PTGMK]?)$/i'strtoupperini_get('post_max_size') ), $p );
    preg_match('/^([0-9]+)([PTGMK]?)$/i'strtoupperini_get('upload_max_filesize') ), $u );
    $arr array('P'=>50,'T'=>40,'G'=>30,'M'=>20,'K'=>10);
    return min(  $p[1] * pow(2,$arr[$p[2]]), $u[1] * pow(2,$arr[$u[2]]) )/(1024*1024)."MB";
}
?>

Monday, May 31, 2010

utf8 in php5




utf8_encode() and utf8_decode() are awful, because they only operate in the ISO-8859-1 (latin1) charset portion of utf8. Also, for reference U+ff01, the ff01 is called the code point.

Lets say I have a unicode character U+4f60 or 你, and I want to echo it in php.

http://www.fileformat.info/info/unicode/char/4f60/index.htm

PHP is not very utf8 friendly, in order to get to work, you have to be using a computer with the right language packs installed, edit the source file in utf8, make sure every page sends out header('Content-type: text/html; charset=utf-8'); and you may still need to echo the utf8 meta tag. And for good measure make sure the file is saved with a utf8 byte order mark. But how do you echo unicode if your source file can only be in the latin1 character set?

One way is to echo the code point. In java "\u4f60" represents the character 你. Not so in php. The best you can do is these:

<?php echo json_decode('"\u4f60"');?>
<?php echo html_entity_decode("&#x4f60;",ENT_QUOTES,"UTF-8");?>
<?php echo "\xE4\xBD\xA0";?> //already encoded in utf8

but there is another way, with 2 basic functions:

function utf8($num)
{
  if($num<=0x7F)    return chr($num);
  if($num<=0x7FF)   return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<=0xFFFF)  return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  if($num<=0x1FFFFreturn chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128).chr(($num&63)+128);
  return '';
}

function uniord($c)
{
  $ord0 ord($c{0}); if ($ord0>=0   && $ord0<=127return $ord0;
  $ord1 ord($c{1}); if ($ord0>=192 && $ord0<=223return ($ord0-192)*64 + ($ord1-128);
  $ord2 ord($c{2}); if ($ord0>=224 && $ord0<=239return ($ord0-224)*4096 + ($ord1-128)*64 + ($ord2-128);
  $ord3 ord($c{3}); if ($ord0>=240 && $ord0<=247return ($ord0-240)*262144 + ($ord1-128)*4096 + ($ord2-128)*64 + ($ord3-128);
  return false;
}

<?php echo utf8(0x4f60);?>

or you can convert back
<?php echo dechex(uniord(utf8(0x4f60)));?>
4f60

Also helpful:
function is_utf8($string
{
  // From http://w3.org/International/questions/qa-forms-utf-8.html
  return preg_match('%^(?:
      [\x09\x0A\x0D\x20-\x7E]      # ASCII
    | [\xC2-\xDF][\x80-\xBF]       # non-overlong 2-byte
    |  \xE0[\xA0-\xBF][\x80-\xBF]    # excluding overlongs
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}  # straight 3-byte
    |  \xED[\x80-\x9F][\x80-\xBF]    # excluding surrogates
    |  \xF0[\x90-\xBF][\x80-\xBF]{2}   # planes 1-3
    | [\xF1-\xF3][\x80-\xBF]{3}      # planes 4-15
    |  \xF4[\x80-\x8F][\x80-\xBF]{2}   # plane 16
  )*$%xs'$string);
  
}

Sunday, May 09, 2010

VirtualBox fullscreen

VBoxSDL -fullscreen -vm <name of virtual machine here>
VBoxSDL -fullscreen -vm XP_mini

Saturday, April 03, 2010

php upload script


<?php
if ($_SERVER['REQUEST_METHOD']=='POST')
{
    //echo ini_get('post_max_size');
    //echo ini_get('upload_max_filesize');
    //echo ini_get('max_input_time');
    //echo ini_get('max_execution_time');
    //echo ini_get('max_file_uploads');
    //echo ini_get('file_uploads');
    $errors = array(
      UPLOAD_ERR_OK =>'There is no error, the file uploaded with success.',
      UPLOAD_ERR_INI_SIZE =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
      UPLOAD_ERR_FORM_SIZE =>'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
      UPLOAD_ERR_PARTIAL =>'The uploaded file was only partially uploaded.',
      UPLOAD_ERR_NO_FILE =>'No file was uploaded.',
      UPLOAD_ERR_NO_TMP_DIR =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.',
      UPLOAD_ERR_CANT_WRITE =>'Failed to write file to disk. Introduced in PHP 5.1.0.',
      UPLOAD_ERR_EXTENSION  =>'A PHP extension stopped the file upload',
    );
    if ($_FILES['userfile']['error']==UPLOAD_ERR_OK)
    { 
        $uploads_dir = '/srv/www/htdocs/files/';
        $tmp_name = $_FILES["userfile"]["tmp_name"];
        $name = $_FILES["userfile"]["name"];
        move_uploaded_file($tmp_name, "$uploads_dir/$name");
        die("complete");
    }
    else
    {
        die($errors[$_FILES['userfile']['error']]);
    }  
}
?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo 200*1024*1024;?>" />
<input name="userfile" type="file" />
<input type="submit" value="Upload" />
</form>

Friday, April 02, 2010

php header for xml utf8


header('Content-Type: text/xml; charset=UTF-8');






source(s): http://www.source.com

Tuesday, March 23, 2010

List Installed Packages (with file sizes) - Ubuntu


dpkg --get-selections | awk '{printf("echo \"%s:\"`sudo aptitude show %s |grep \"Uncompressed Size:\"` \n", $1, $1 );}' >output.sh
sh output.sh| awk -F: '{printf("%s:%s\n",$1,$3);}' >list.txt
rm output.sh

Monday, February 22, 2010

ubuntu hamachi

There is no .deb in the ubuntu 9.10 rep for hamachi or quamachi. Have no fear, you can install it via the autopackage system. Just download the .package files and satisfy dependencies, and run the package files.


1. Go to http://code.google.com/p/quamachi/
2. download hamachi and quamachi, ex:
http://quamachi.googlecode.com/files/quamachi-0.4.1-1.package
http://quamachi.googlecode.com/files/hamachi-0.9.9.9-20.package
3. sudo apt-get install python libqt4-core python-qt4 pyqt4-dev-tools upx-ucl grep bash make
4. chmod 777 hamachi-0.9.9.9-20.package
5. chmod 777 quamachi-0.4.1-1.package
6. sudo ./hamachi-0.9.9.9-20.package
7. sudo ./quamachi-0.4.1-1.package

Monday, January 25, 2010

VirtualBox - Start up Virtual Machine without gui

So you can ssh into it or whatever

VBoxManage startvm "windows xp" --type headless
VBoxManage controlvm "windows xp" poweroff

Tuesday, January 19, 2010

virtualbox - convert img file to vdi


VBoxManage convertfromraw -format VDI [filename].img [filename].vdi

source(s): http://mdm-adph.blogspot.com/2009/05/using-img-files-with-virtualbox-to-test.html

Monday, January 18, 2010

mysql - get rid of pipe delimiter, and auto escaping

mysql --silent
> select '\\';
\\

When using IO redirection, mysql commandline automatically enters --silent or --batch mode, and auto escapes the output. -r (--raw) is the fix.

mysql -r --silent
> select '\\';
\


mysql -r -D digicert_com < somequery.txt > Desktop/r-queries.txt

source(s): http://bugs.mysql.com/bug.php?id=35122

Tuesday, January 12, 2010

VirtualBox copy harddrive to new uuid

This should work fine with vdi and vmdk files.
VBoxManage clonevdi myhardrive.vdi


source(s): http://www.brianjester.us/blog/index.php?entry=entry080720-165143