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:
- 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 ?> - 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).
- 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 ?> - The Java program takes the encrypted.pdf and write out the decrypted.pdf which should be the same as the plain.pdf.