Warning: fopen(/home/partdesi/public_html/propaso/blog/wp-content/cache/wp_cache_mutex.lock) [function.fopen]: failed to open stream: Permission denied in /home/partdesi/public_html/propaso/blog/wp-content/plugins/wp-cache/wp-cache-phase2.php on line 96
Fun Things in Life » Java

Archive for the ‘Java’ Category

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”.

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.