암호 레벨은 높지 않지만, 비교적 짧은 암호화URL과 복호화가 가능한 로직입니다.
// 참고 : http://naveensnayak.wordpress.com/2013/03/12/simple-php-encrypt-and-decr...
function encrypt_decrypt( $action, $string, $saltkey=null ) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = '이 곳에 secret key를 지정하시오';
if ( $saltkey ) { $secret_key = $saltkey; }
$secret_iv = '이 곳에 secret iv를 지정하시오';
// $stringに+が入っていると、空白になってbase64_decode($string)から問題が発生するので。
$string = str_replace( " ", "+", $string );
// debug( $string );
// 暗号化URLに追加されてない,,(base64の==)を追加する。
if ( "decrypt" == $action && ",," == substr( $string, -2 ) ) {
$string .= ",,";
}
// hash
$key = hash('sha256', $secret_key);
$iv = hash('sha256', $secret_iv);
if( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, $iv);
$output = base64_url_encode($output);
}
else if( $action == 'decrypt' ){
$output = $decryptedMessage = openssl_decrypt(base64_url_decode($string), $encrypt_method, $key, $iv);
}
// 暗号化URLに,,(base64の==)をなくすため。
if ( "encrypt" == $action && ",," == substr( $output, -2 ) ) {
$output = substr( $output, 0, -2 );
}
return $output;
}
// http://jp2.php.net/manual/en/function.base64-encode.php
function base64_url_encode($input)
{
return strtr(base64_encode($input), '+/=', '-_,');
}
function base64_url_decode($input)
{
return base64_decode(strtr($input, '-_,', '+/='));
}
이용 예)
$ticket_id = "암호화하고 싶은 티켓 번호를 넣으세요";
$encrypted_ticket_id = encrypt_decrypt('encrypt', $ticket_id);
$ticket_url = "http://".$_SERVER['HTTP_HOST']."/project/?ticket_id=".$encrypted_ticket_id;
echo "티켓 발급 결과 <a href='".$ticket_url."' target='_blank'>URL</a>는, <br/>".$ticket_url;
echo "<hr />";
$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_ticket_id);
echo "Decrypted Text = $decrypted_txt\n";
echo "<hr />";
암호화 레벨이 높지 않으므로, 개인정보를 다루는 분야에는 사용하지 않는 게 좋을지도...
댓글 쓰기