Archive for the ‘Programming’ Category

Simple Bash Email Validator

Thursday, October 2nd, 2008

A lot of time, I need to validate an email address.  There are a lot of PHP/ASP/etc, etc scripts out there to do email validation either based on formatting or connecting back to the SMTP to perform a check.  However, I don’t seem to find any of the validation scripts based on Bash.  Here’s my version:

#!/bin/bash
# check for valid usage
if [ x$1 = 'x' ]
then
echo "Usage: $0 <email address>"
exit 1
fi

# grabbing fields
user=`echo $1 | cut -f1 -d\@`
host=`echo $1 | cut -f2 -d\@`
mxhost=`host -t mx $host | cut -f7 -d\ `
len=`echo $mxhost | wc -c`
len=`expr $len - 2`
mxhost=`echo $mxhost | cut -b1 -$len`

# compose email commands
echo -ne "helo test.com\r\n" > mailcmd
echo -ne "mail from: test\@test.com\r\n" >> mailcmd
echo -ne "rcpt to: $1\r\n" >> mailcmd
echo -ne "quit\r\n" >> mailcmd

# check for mail results
mailresult=`cat mailcmd | nc $mxhost 25| grep ^550 | wc -c`

if [ $mailresult -eq 0 ]
then
echo $1 "is valid"
exit 0
else
echo $1 "is not valid"
exit 1
fi

# clean up
rm mailcmd

AES Interop Between PHP and Java (Part 4)

Saturday, May 19th, 2007

… “After started something, you have to finish it” my dad used to tell me…

The Problem: Part 3 was to encrypt a binary file (PDF) in PHP and decrypt it over in Java. It is of course natural to complete it to do it the other way around.

This is actually just flipping some code, real simple, just that I am so busy recently that I have not made time for it.

The Solution:

  1. Encrypt a message in Java:
    001	import java.io.*;
    002	import javax.crypto.*;
    003	import javax.crypto.spec.*;
    004
    005	public class encrypt {
    006	  public static void main(String args[]) throws Exception {
    007	    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    008	    SecretKeySpec keySpec =
    009	      new SecretKeySpec("01234567890abcde".getBytes(), "AES");
    010	    IvParameterSpec ivSpec =
    011	      new IvParameterSpec("fedcba9876543210".getBytes());
    012	    cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    013	    FileInputStream fis   =
    014	      new FileInputStream(new File("plain.pdf"));
    015	    CipherInputStream cis = new CipherInputStream(fis, cipher);
    016	    FileOutputStream fos  =
    017	      new FileOutputStream(new File("encrypted.pdf"));
    018
    019	    byte[] b = new byte[8];
    020	    int i;
    021
    022	    while ((i = cis.read(b)) != -1) {
    023	      fos.write(b, 0, i);
    024	    }
    025	    fos.flush(); fos.close();
    026	    cis.close(); fis.close();
    027	  }
  2. The above Java program will encrypted PDF file. It takes the unencrypted PDF file (plain.pdf) and create encrypted.pdf (the encrypted file).
  3. Now with the encrypted.pdf, we use a PHP program to decrypt it:
    001	<?php
    002	  $secret_key   = "01234567890abcde";
    003	  $iv           = "fedcba9876543210";
    004	  $infile       = "encrypted.pdf";
    005	  $outfile      = "decrypted.pdf";
    006
    007	  $crypttext = file_get_contents($infile);
    008	  $plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128,
    009	                 $secret_key, $crypttext, MCRYPT_MODE_CBC, $iv);
    010
    011	  header('Content-Type: application/octet-stream');
    012	  header('Content-Length: ' . strlen($plaintext));
    013	  header('Content-Disposition: attachment; filename=' . ($outfile));
    014	  echo $plaintext;
    015	?>
  4. The PHP program takes the encrypted.pdf and force download the decrypted.pdf which should be the same as the plain.pdf.

AES Interop Between PHP and Java (Part 3)

Friday, April 20th, 2007

… Answer a call for help, hopefully I would get the same when I call for help …

The Problem: Part 1 and Part 2 has been quite interesting. I was thinking of what to do next and Robi Ilham asked me to try to solve the problem of encrypting a PDF file (in PHP) and decrypting it in Java.

Now this seems hard, but once you look at how it is done, this is pretty simple stuff. You just need to know the appropriate tools to use and right encryption method (in this case, AES).

The Solution:

  1. Encrypt a message in PHP and force it down the browser:
    001	<?php
    002	  $secret_key   = "01234567890abcde";
    003	  $iv           = "fedcba9876543210";
    004	  $infile       = "plain.pdf";
    005	  $outfile      = "encrypted.pdf";
    006
    007	  $plaintext = file_get_contents($infile);
    008	  $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128,
    009                      $secret_key, $plaintext, MCRYPT_MODE_CBC, $iv);
    010
    011	  header('Content-Type: application/octet-stream');
    012	  header('Content-Length: ' . strlen($crypttext));
    013	  header('Content-Disposition: attachment; filename=' . ($outfile));
    014	  echo $crypttext;
    015	?>
  2. The above PHP program will force an encrypted PDF file down from your browser. It takes the unencrypted PDF file (plain.pdf) and force a download of encrypted.pdf (the encrypted file).
  3. Now after saving the encrypted.pdf, we use a Java program to decrypt it:
    001	import java.io.*;
    002	import javax.crypto.*;
    003	import javax.crypto.spec.*;
    004
    005	public class decrypt {
    006	  public static void main(String args[]) throws Exception {
    007	    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    008	    SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
    009	    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    010	    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    011
    012	    FileInputStream fis   = new FileInputStream(new File("encrypted.pdf"));
    013	    CipherInputStream cis = new CipherInputStream(fis, cipher);
    014	    FileOutputStream fos  = new FileOutputStream(new File("decrypted.pdf"));
    015
    016	    byte[] b = new byte[8];
    017	    int i;
    018
    019	    while ((i = cis.read(b)) != -1) {
    020	      fos.write(b, 0, i);
    021	    }
    022	    fos.flush(); fos.close();
    023	    cis.close(); fis.close();
    024	?>
  4. The Java program takes the encrypted.pdf and write out the decrypted.pdf which should be the same as the plain.pdf.

AES Interop Between PHP and Java (Part 2)

Monday, March 12th, 2007

… Give him a fish; you fed him for today. Teach him how to fish; you fed him for life …

The Problem: In a previous post, I show how to use AES in PHP to encrypt a message and decrypt it in Java. Then Amit asked if it could be done the other way around.

Again, without all the knowledge about AES, Key, CBC, ECB, etc, etc… I will present a simple solution. Keep in mind, these are bits and pieces, so that I wouldn’t take all the fun out of you. I will just show you how to encrypt and decrypt and you can implement other things in between so that you can also have the fun.

The Solution:

  1. Encrypt a message in Java:
    001	import javax.crypto.*;
    002	import javax.crypto.spec.*;
    003	import java.security.*;
    004	import java.io.*;
    005
    006	public class tester {
    007	  public static String bytesToHex(byte[] data) {
    008	    if (data==null) {
    009	      return null;
    010	    } else {
    011	      int len = data.length;
    012	      String str = "";
    013	      for (int i=0; i<len; i++) {
    014	        if ((data[i]&0xFF)<16)
    015	          str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
    016	        else
    017               str = str + java.lang.Integer.toHexString(data[i]&0xFF);
    018	      }
    019	    return str;
    020	  }
    021
    022	  public static void main(String[] args) throws Exception {
    023	    String plaintext = "Hello World     ";
    024         String key = "01234567890abcde";
    025         String iv = "fedcba9876543210";
    026
    027         SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
    028         IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
    029
    030	    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    031	    cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
    032	    byte[] encrypted = cipher.doFinal(plaintext.getBytes());
    033
    034         System.out.println("Encrypted: " + bytesToHex(encrypted));
    035
    036         cipher.init(Cipher.DECRYPT_MODE,keyspec,ivspec);
    037	    byte[] decrypted = cipher.doFinal(encrypted);
    038	    System.out.println(new String(decrypted));
    039	  }
    040	}
  2. The output of the Java program should be “444e6969a269829a3e59a86300614fc5″. Take note that I cheated by making the plain text message as “Hello World ” (16 bytes). You can work out the padding part of Java program (or someone is nice enough to put it in the comment).
  3. We just take the output and decrypt it over in the following PHP program:
    001	<?php
    002	function hex2bin($hexdata) {
    003	  $bindata="";
    004
    005	  for ($i=0;$i<strlen($hexdata);$i+=2) {
    006	   $bindata.=chr(hexdec(substr($hexdata,$i,2)));
    007	  }
    008
    009	  return $bindata;
    010	}
    011
    012	$cipher     = "rijndael-128";
    013	$mode       = "cbc";
    014	$secret_key = "01234567890abcde";
    015	$iv         = "fedcba9876543210";
    016
    017	$td = mcrypt_module_open($cipher, "", $mode, $iv);
    018
    019	mcrypt_generic_init($td, $secret_key, $iv);
    020	$decrypted_text = mdecrypt_generic($td, hex2bin("444e6969a269829a3e59a86300614fc5"));
    021	echo trim($decrypted_text);
    022	mcrypt_generic_deinit($td);
    023	mcrypt_module_close($td);
    024	?>
  4. The output should be “Hello World”.

Making a Simple PHP Captcha that Works

Wednesday, February 7th, 2007

… Learning is a life long process, if you stop, life stops …

The Problem: I have an email form on my Website, and keep getting these spams “to make my love life better”. While that might be a good intension, I rather not receiving those emails. So, I decided to put a captcha to reduce the number of spams.

I have found bits and pieces on the Web on how to generate a captcha but most of them don’t present a total solution. I will put them all together and hope that this will ease the process of learning.

The Solution: I have this captcha program that generates an image and set a cookie. Then I wrote a html form and a php program that uses this captcha. We first create a php program (captcha.php) that generates the image and set the cookie:

001	<?php
002	function getR($col) {return ( ( $col >> 8 ) >> 8 ) % 256;}
003	function getG($col) {return ( $col >> 8 ) % 256;}
004	function getB($col) {return $col % 256;}
005
006	function create_image() {
007	  $bcol       = array(0,0,0); // background color
008	  $fcol       = array(255,228,250); // foreground color
009	  $words      = array('apple','badge','black'); // words for captcha
010	  $fact       = 2;
011	  $font       = 5;
012	  $cosrate    = rand(10,19);
013	  $sinrate    = rand(10,18);
014	  $charwidth  = imagefontwidth($font);
015	  $charheight = imagefontheight($font);
016	  $pass       = $words[rand(0,sizeof($words)-1)];
017	  $strlen     = strlen($pass);
018	  $width      = ($strlen + 2) * $charwidth;
019	  $height     = 2 * $charheight;
020
021	  session_start();
022	  $_SESSION["pass"] = $pass;
023
024	  $im   = @imagecreatetruecolor($width, $height)
025	            or die("Cannot Initialize new GD image stream");
026	  $im2  = imagecreatetruecolor($width*$fact, $height*$fact);
027	  $bcol = imagecolorallocate($im, $bcol[0], $bcol[1], $bcol[2]);
028	  $fcol = imagecolorallocate($im, $fcol[0], $fcol[1], $fcol[2]);
029
030	  imagefill($im, 0, 0, $bcol);
031	  imagefill($im2, 0, 0, $bcol);
032	  $dotcol  = imagecolorallocate($im, (abs(getR($fcol)-getR($bcol)))/2.5,
033	                                     (abs(getG($fcol)-getG($bcol)))/2.5,
034	                                     (abs(getB($fcol)-getB($bcol)))/2.5);
035	  $dotcol2 = imagecolorallocate($im, (abs(getR($fcol)-getR($bcol)))/1.5,
036	                                     (abs(getG($fcol)-getG($bcol)))/1.5,
037	                                     (abs(getB($fcol)-getB($bcol)))/3.5);
038	  $linecol = imagecolorallocate($im, (abs(getR($fcol)-getR($bcol)))/2.4,
039	                                     (abs(getG($fcol)-getG($bcol)))/2.1,
040	                                     (abs(getB($fcol)-getB($bcol)))/2.5);
041
042	  for($i=0; $i<$width; $i=$i+rand(1,5)) {
043	    for($j=0; $j<$height; $j=$j+rand(1,5)) {
044	      imagesetpixel($im, $i, $j, $dotcol);
045	    }
046	  }
047
048	  imagestring($im, $font, $charwidth, $charheight/2, $pass, $fcol);
049
050	  for($j=0; $j<$height*$fact; $j=$j+rand(3,6)) {
051	    imageline($im2, 0, $j, $width*$fact, $j, $linecol);
052	  }
053
054	  for($i=0; $i<$width*$fact; $i=$i+rand(4,9)) {
055	    imageline($im2, $i, 0, $i, $height*$fact, $linecol);
056	  }
057
058	  for($i=0; $i<$width*$fact; $i++) {
059	    for($j=0; $j<$height*$fact; $j++) {
060	      $x = abs(((cos($i/$cosrate)*5+sin($j/$sinrate*2)*2+$i)/$fact))%$width;
061	      $y = abs(((sin($j/$sinrate)*5+cos($i/$cosrate*2)*2+$j)/$fact))%$height;
062	      $col = imagecolorat($im, $x, $y);
063	      if ($col!=$bcol) imagesetpixel($im2, $i, $j, $col);
064	    }
065	  }
066
067	  for($j=0; $j<$height*$fact; $j=$j+rand(1,5)) {
068	    for($i=0; $i<$width*$fact; $i=$i+rand(1,5)) {
069	      imagesetpixel($im2, $i, $j, $dotcol2);
070	    }
071	  }
072
073	  imagejpeg($im2);
074	  imagedestroy($im);
075	  imagedestroy($im2);
076	}
077
078	header("Content-Type: image/jpeg");
079	create_image();
080	?>

You can try modifying line 7 and 8 for different background and foreground colour to see the effect. Line 9 are the words that are used randomly for generating the captcha (you can add as many as you wish). Then the html form (testcaptcha.html):

001	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
002	  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
003	<html xmlns="http://www.w3.org/1999/xhtml">
004	<head>
005	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
006	<title>Captcha Test</title>
007	<style type="text/css">
008	<!--
009	  body,td,th {
010	  font-family: Arial, Helvetica, sans-serif;
011	  }
012	-->
013	</style></head>
014	<body>
015	  <form id="captcha_form" name="captcha_form" method="post" action="testcaptcha.php">
016	    <img src="captcha.php" /><input name="userpass" type="text" />
017	    <input name="submit" type="submit" value="Submit" /></td>
018	  </form>
019	</body>
020	</html>

and finally the php program to process the form (testcaptcha.php):

001	<?php
002	session_start();
003	if ($_SESSION["pass"] == $_POST["userpass"]) {
004	  echo "You have got the captcha right!";
005	} else {
006	  echo "Sorry you failed the captcha";
007	}
008	?>

This example should get you up and running immediately. Hope you can have fun playing with the example.

AES Interop Between PHP and Java (Part 1)

Saturday, January 27th, 2007

… Life is never easy, learning takes time. Hope this will help someone out there …

The Problem: I want to encrypt a message in PHP using AES and then take it to a Java program to decrypt it.

Without all the knowledge about AES, Key, CBC, ECB, etc, etc… I will present a simple solution. Keep in mind, these are bits and pieces, so that I wouldn’t take all the fun out of you. I will just show you how to encrypt and decrypt and you can implement other things in between so that you can also have the fun.

The Solution:

  1. We are using mcrypt with PHP. The encryption program in PHP:
    001	<?php
    002	  $cipher     = "rijndael-128";
    003	  $mode       = "cbc";
    004	  $plain_text = "Hello World";
    005	  $secret_key = "01234567890abcde";
    006	  $iv         = "fedcba9876543210";
    007
    008	  td = mcrypt_module_open($cipher, "", $mode, $iv);
    009	  mcrypt_generic_init($td, $secret_key, $iv);
    010	  $cyper_text = mcrypt_generic($td, $plain_text);
    011	  echo bin2hex($cyper_text);
    012	  mcrypt_generic_deinit($td);
    013	  mcrypt_module_close($td);
    014	?>
  2. The output from the above program should be “ac5c3404f57a5061f36a694eb5d56214″
  3. We just take the output and decrypt it over in the following Java program:
    001	import javax.crypto.spec.IvParameterSpec;
    002	import javax.crypto.Cipher;
    003	import java.security.MessageDigest;
    004	import java.security.NoSuchAlgorithmException;
    005	import java.lang.Exception;
    006	import javax.crypto.spec.SecretKeySpec;
    007	import javax.crypto.SecretKey;
    008	import java.io.IOException;
    009
    010	public class tester {
    011	  public static byte[] hexToBytes(String str) {
    012	    if (str==null) {
    013	      return null;
    014	    } else if (str.length() < 2) {
    015	      return null;
    016	    } else {
    017	      int len = str.length() / 2;
    018	      byte[] buffer = new byte[len];
    019	      for (int i=0; i<len; i++) {
    020	        buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
    021	      }
    022	      return buffer;
    023	    }
    024	  }
    025
    026	  public static void main(String [] args) throws Exception {
    027	    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    028	    SecretKeySpec keySpec = new SecretKeySpec("01234567890abcde".getBytes(), "AES");
    029	    IvParameterSpec ivSpec = new IvParameterSpec("fedcba9876543210".getBytes());
    030	    cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
    031	    byte[] outText = cipher.doFinal(hexToBytes("ac5c3404f57a5061f36a694eb5d56214"));
    032	    System.out.println(new String(outText).trim());
    033	  }
    034	}
  4. The output from the Java program should be “Hello World”. Take note that on line 31, we put in the output from PHP.