четверг, 22 ноября 2007 г.

Связываем PHP и Java через AES шифрование

Задача: нужно зашифровать сообщение на PHP чтобы расшифровать его в Java.

Решение:
1. Использование mcrypt в 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);

2. Вывод должен быть следующим:
"ac5c3404f57a5061f36a694eb5d56214"

3. Съедаем данные на выходе Java программой для того чтобы расшифровать


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; i020 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 }

Оригинал: http://propaso.com/blog/?p=4