Welcome to Srini's blog

Thursday, December 31, 2009

Encrypt in JAVA and Decrypt in PHP & Encrypt in PHP and Decrypt in JAVA

Encrypt in JAVA and decrypt in PHP:

1. Encryption in JAVA:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Crypto {
//iv length should be 16 bytes
private String iv = "fedcba9876543210";
private String key = null;
private Cipher cipher = null;
private SecretKeySpec keySpec = null;
private IvParameterSpec ivSpec = null;

/**
* Constructor
*
* @throws Exception
*/
public Crypto(String key) throws Exception {
this.key = key;

// Make sure the key length should be 16
int len = this.key.length();
if(len < 16) {
int addSpaces = 16 - len;
for (int i = 0; i < addSpaces; i++) {
this.key = this.key + " ";
}
} else {
this.key = this.key.substring(0, 16);
}
this.keySpec = new SecretKeySpec(this.key.getBytes(), "AES");
this.ivSpec = new IvParameterSpec(iv.getBytes());
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
}

/**
* Bytes to Hexa conversion
*
* @param data
* @return
*/
public String bytesToHex(byte[] data) {
if (data == null) {
return null;
} else {
int len = data.length;
String str = "";
for (int i = 0; i < len; i++) {
if ((data[i] & 0xFF) < 16)
str = str + "0" + java.lang.Integer.toHexString(data[i] & 0xFF);
else
str = str + java.lang.Integer.toHexString(data[i] & 0xFF);
}
return str;
}
}

/** Encrpt the goven string
*
* @param plainData
* @throws Exception
*/
public String encrypt(String plainData) throws Exception {

// Make sure the plainData length should be multiple with 16
int len = plainData.length();
int q = len / 16;
int addSpaces = ((q + 1) * 16) - len;
for (int i = 0; i < addSpaces; i++) {
plainData = plainData + " ";
}

this.cipher.init(Cipher.ENCRYPT_MODE, this.keySpec, this.ivSpec);
byte[] encrypted = cipher.doFinal(plainData.getBytes());

return bytesToHex(encrypted);
}

public static void main(String[] args) throws Exception {
Crypto c = new Crypto("D4:6E:AC:3F:F0:BE");
String encrStr = c.encrypt("Hello World");
System.out.println("Encrypted Str :" + encrStr);
}
}
2. After run this program we will get encrypted str, Now decrypt this str using PHP
3. Decryption in PHP
$cipher = "rijndael-128";
$mode = "cbc";
$secret_key = "D4:6E:AC:3F:F0:BE";
//iv length should be 16 bytes
$iv = "fedcba9876543210";

// Make sure the key length should be 16 bytes
$key_len = strlen($secret_key);
if($key_len < 16 ){
$addS = 16 - $key_len;
for($i =0 ;$i < $addS; $i++){
$secret_key.=" ";
}
}else{
$secret_key = substr($secret_key, 0, 16);
}

$td = mcrypt_module_open($cipher, "", $mode, $iv);
mcrypt_generic_init($td, $secret_key, $iv);
$decrypted_text = mdecrypt_generic($td, hex2bin("444e6969a269829a3e59a86300614fc5"));
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
echo trim($decrypted_text);

function hex2bin($hexdata) {
$bindata="";
for ($i=0;$i $bindata.=chr(hexdec(substr($hexdata,$i,2)));
}
return $bindata;
}
?>
4. You will get decrypted str as "Hello World".



Encrypt in PHP and decrypt in JAVA:

1. Encryption in PHP:
$cipher = "rijndael-128";
$mode = "cbc";
$secret_key = "D4:6E:AC:3F:F0:BE";
//iv length should be 16 bytes
$iv = "fedcba9876543210";

// Make sure the key length should be 16 bytes
$key_len = strlen($secret_key);
if($key_len < 16 ){
$addS = 16 - $key_len;
for($i =0 ;$i < $addS; $i++){
$secret_key.=" ";
}
}else{
$secret_key = substr($secret_key, 0, 16);
}

$td = mcrypt_module_open($cipher, "", $mode, $iv);
mcrypt_generic_init($td, $secret_key, $iv);
$cyper_text = mcrypt_generic($td, "Hello World");
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
echo bin2hex($cyper_text);
?>
2. After run this program we will get encrypted str, Now decrypt this str using JAVA
3. Decryption in JAVA

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Crypto {
//iv length should be 16 bytes
private String iv = "fedcba9876543210";
private String key = null;
private Cipher cipher = null;
private SecretKeySpec keySpec = null;
private IvParameterSpec ivSpec = null;

/**
* Constructor
*
* @throws Exception
*/
public Crypto(String key) throws Exception {
this.key = key;

// Make sure the key length should be 16
int len = this.key.length();
if(len < 16) {
int addSpaces = 16 - len;
for (int i = 0; i < addSpaces; i++) {
this.key = this.key + " ";
}
} else {
this.key = this.key.substring(0, 16);
}
this.keySpec = new SecretKeySpec(this.key.getBytes(), "AES");
this.ivSpec = new IvParameterSpec(iv.getBytes());
this.cipher = Cipher.getInstance("AES/CBC/NoPadding");
}

/**
* Hexa to Bytes conversion
*
* @param str
* @return
*/
public byte[] hexToBytes(String str) {
if (str == null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i = 0; i < len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
}
return buffer;
}
}

/** Decrypt the given excrypted string
*
* @param encrStr
* @throws Exception
*/
public String decrypt(String encrData) throws Exception {
this.cipher.init(Cipher.DECRYPT_MODE, this.keySpec, this.ivSpec);
byte[] outText = this.cipher.doFinal(hexToBytes(encrData));

String decrData = new String(outText).trim();
return decrData;
}
public static void main(String[] args) throws Exception {
Crypto c = new Crypto("D4:6E:AC:3F:F0:BE");
String decrStr = c.decrypt("444e6969a269829a3e59a86300614fc5");
System.out.println("Decrypted Str :" + decrStr);
}
}
4. You will get decrypted str as "Hello World".

8 comments:

  1. Good article!!

    But one pblm .

    This line got error :

    -------------------------------------------------------
    for ($i=0;$i $bindata.=chr(hexdec(substr($hexdata,$i,2)));

    -------------------------------------------------------
    I didn't understand what u were trying to do with this line.

    its in section 3. Decryption in PHP .

    ReplyDelete
    Replies
    1. fix the line 28

      function hex2bin($data){
      $bin = "";
      $i = 0;
      do {
      $bin .= chr(hexdec($data{$i}.$data{($i + 1)}));
      $i += 2;
      } while ($i < strlen($data));

      return $bin;
      }

      Delete
    2. Somethnig like that:

      for ($i=0;$i<strlen($hexdata);$i+=2) {
      $bindata.=chr(hexdec(substr($hexdata,$i,2)));
      }
      return $bindata;
      }

      Could you help please ?

      Anyway great article !!! Thanks

      Delete
    3. The last post give the solution for the code copy/paste mistake...

      Delete
  2. you code dont work!!!

    Parse error: syntax error, unexpected T_VARIABLE, expecting ';' in C:\xampp\htdocs\aesDeprypt.php on line 28

    ReplyDelete
  3. It's great code.... i have succesfully encrypt from php and decrypt in java...thanks guys..

    ReplyDelete