PHP

[PHP][암호화] AES 128bit 암호화(CBC)

은둔한량 2015. 4. 7. 13:38
반응형

<?

class AES_128

{

 

function __construct()

{

}

 

function PKCS5Pad($text, $blocksize = 16)

{

$pad = $blocksize - (strlen($text) % $blocksize);

return $text . str_repeat(chr($pad), $pad);

}

 

function PKCS5Unpad($text)

{

$pad = ord($text{strlen($text)-1});

if ($pad > strlen($text)) return $text;

if (!strspn($text, chr($pad), strlen($text) - $pad)) return $text;

return substr($text, 0, -1 * $pad);

}

 

function encrypt($iv,$key,$str)

{

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

@mcrypt_generic_init($td, $key, $iv);

$encrypted = @mcrypt_generic($td, $this->PKCS5Pad(($str)));

 

mcrypt_generic_deinit($td);

mcrypt_module_close($td);

return ($encrypted);

}

 

function decrypt($iv,$key,$code)

{

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

@mcrypt_generic_init($td, $key, $iv);

$decrypted = @mdecrypt_generic($td, $code);

 

mcrypt_generic_deinit($td);

mcrypt_module_close($td);

return ($this->PKCS5Unpad($decrypted));

}

 

function AESCBCPKCS5($source_data, $key, $iv, $mode = "enc", $base64 = "yes")

{

if($mode=="dec")

{

if($base64=="yes") return $this->decrypt($iv,$key,base64_decode($source_data));

else return $this->decrypt($iv,$key,$source_data);

}

else

{

if($base64=="yes") return base64_encode($this->encrypt($iv,$key,$source_data));

else $this->encrypt($iv,$key,$source_data);

}

}

}

?>

 

* 인터넷에서 떠돌아 다니는 소스들 도움을 많이 받았습니다.

* 다음과 같이 사용하시면 됩니다.

 

<?

require_once ('AES_128.php');

 

$key = "0123456789abcdef";

$IV = "fedcba9876543210";

$str = "ABCDEFG";

 

$AES_128= new AES_128();

$tmp_str = $AES_128 -> AESCBCPKCS5($str, $key, $IV, "enc", "yes");

echo "tmp_encrypt => $tmp_str<br>";

 

$tmp_str = $AES_128 -> AESCBCPKCS5($tmp_str, $key, $IV, "dec", "yes");

echo "tmp_decrypt => $tmp_str<br>";

 

?> 

  

mcrypt_module 설치가 되어야 함   yum install php-mcrypt 로 설치

 

 

-------------------------------------------------------------------------------------------------------

* 대칭키 AES256 = C# + Objective C(ios) + PHP + JAVA(Android) + Perl + Javascript

http://www.imcore.net/encrypt-decrypt-aes256-c-objective-ios-iphone-ipad-php-java-android-perl-javascript/

 

반응형