AES Encrypt, Decrypt between Java & PHP

โค้ดนี้มีแหล่งที่มาจาก http://schneimi.wordpress.com/2008/11/25/aes-128bit-encryption-between-java-and-php
โดยมีการดัดแปลงเล็กน้อย เพื่อเปลี่ยนข้อมูลจากเดิมที่ใช้ Hex String เป็น input/output มาเป็น Base64 String เพื่อลด Overhead จาก 100% เป็น 33.33%
วัตถุประสงค์เพื่อใช้ในการรับส่งข้อมูลที่มีการเข้ารหัสระหว่าง Android (Java) และ Server (PHP) โดยโค้ดจะมีบางส่วนที่ใช้ lib ของ Base64 จาก commons-codec-1.4.jar
สำหรับวิธีการเรียกใช้งานก็ง่ายๆดังนี้

Java AES Encrypt & Decrypt
String encrypted =  mcrypt.encrypt(“Text to Encrypt”);
String decrypted = mcrypt.decrypt(“mXXijfBVwzaptwkLA/iGiQ==”);

PHP AES Encrypt & Decrypt
$encrypted = $this->mcrypt->encrypt(‘Text to Encrypt’);
$decrypted = $this->mcrypt->decrypt(“mXXijfBVwzaptwkLA/iGiQ==”);

MCrypt.java
public class MCrypt {

	private String iv = "fedcba9876543210";// Dummy iv (CHANGE IT!)
	private IvParameterSpec ivspec;
	private SecretKeySpec keyspec;
	private Cipher cipher;

	private String SecretKey = "0123456789abcdef";// Dummy secretKey (CHANGE
													// IT!)

	public MCrypt() {
		ivspec = new IvParameterSpec(iv.getBytes());
		keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
		try {
			cipher = Cipher.getInstance("AES/CBC/NoPadding");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		}
	}

	public String encrypt(String text) throws Exception {
		if (text == null || text.length() == 0)
			throw new Exception("Empty string");

		byte[] encrypted = null;

		try {
			cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

			encrypted = cipher.doFinal(padString(text).getBytes());
		} catch (Exception e) {
			throw new Exception("[encrypt] " + e.getMessage());
		}
		return Base64.encodeBase64String(encrypted);
	}

	public byte[] decrypt(String code) throws Exception {
		if (code == null || code.length() == 0)
			throw new Exception("Empty string");

		byte[] decrypted = null;

		try {
			cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
			decrypted = cipher.doFinal(Base64.decodeBase64(code));
		} catch (Exception e) {
			throw new Exception("[decrypt] " + e.getMessage());
		}
		return decrypted;
	}
	private static String padString(String source) {
		char paddingChar = ' ';
		int size = 16;
		int x = source.length() % size;
		int padLength = size - x;

		for (int i = 0; i < padLength; i++) {
			source += paddingChar;
		}

		return source;
	}
}
MCrypt.php
class MCrypt {

    private $iv = 'fedcba9876543210'; #Same as in JAVA
    private $key = '0123456789abcdef'; #Same as in JAVA

    function __construct() {

    }

    function encrypt($str) {
        $iv = $this->iv;

        $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);

        mcrypt_generic_init($td, $this->key, $iv);
        $str = $this->padString($str);
        $encrypted = mcrypt_generic($td, $str);

        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        return base64_encode($encrypted);
    }

    function decrypt($code) {
        $code = base64_decode($code);
        $iv = $this->iv;

        $td = mcrypt_module_open('rijndael-128', '', 'cbc', $iv);

        mcrypt_generic_init($td, $this->key, $iv);
        $decrypted = mdecrypt_generic($td, $code);

        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);

        return utf8_encode(trim($decrypted));
    }

    protected function hex2bin($hexdata) {
        $bindata = '';

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

        return $bindata;
    }

    private function padString($source) {
        $paddingChar = ' ';
        $size = 16;
        $x = strlen($source) % $size;
        $padLength = $size - $x;

        for ($i = 0; $i < $padLength; $i++) {
            $source .= $paddingChar;
        }

        return $source;
    }

}
This entry was posted in Developer, Uncategorized and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>