[PHP]ファイルを暗号化したり復号化したり

セキュリティ云々
最近PHPでいろいろと開発をさせて頂いています
その中で、画像ファイルをサーバ上にアップロードするものが有りました
単純に画像ファイルをアップロード、ってのは良いのですが、単純にそんな感じにしちゃうとHTMLで画像参照するためにはファイルを公開ディレクトリに配置する必要があります
いっちおうサーバから画像ファイルだけ抜き出されてもええように暗号化せよとのお達し
でも簡単!PHPならね!
PHPだったら暗号化と復号化するための関数が良いされているから簡単!!
openssl_encrypt – データを暗号化
openssl_decrypt – データを復号化
さて、めんどくさいので簡単に使えるようにクラス作っちゃいます
あれしてこれして
だだだだっと
できたのがこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | <?php //暗号化パラメータ define( 'PASSWORD' , 'passworddayooo' ); // 任意の文字列 define( 'IV' , '1234567890123456' ); // 16桁で指定 class CryptionUtil { /** * データを暗号化する * @param [type] $plain_file [description] * @return [type] [description] */ public static function encData( $plain_data ) { //パラメータ設定 $password = PASSWORD; $method = 'aes-256-cbc' ; $options = OPENSSL_RAW_DATA; $iv = IV; //暗号化 $enc_data = openssl_encrypt( $plain_data , $method , $password , $options , $iv ); //暗号化済みデータを返す return $enc_data ; } /** * データを復号化する * @param [type] $enc_file [description] * @return [type] [description] */ public static function decData( $enc_data ) { //パラメータ設定 $password = PASSWORD; $method = 'aes-256-cbc' ; $options = OPENSSL_RAW_DATA; $iv = IV; //復号化 $dec_data = openssl_decrypt( $enc_data , $method , $password , $options , $iv ); //復号化済みデータを返す return $dec_data ; } } |
使うときはこんな感じに使います
ファイルを読み込んで、暗号化して上書き保存
1 2 3 4 | $file = $path . 'sample.jpeg' ; $plane_data = file_get_contents ( $file ); $enc_data = CryptionUtil::encData( $plane_data ); file_put_contents ( $file , $enc_data ); |
暗号化ファイルを読み込んでhttpで画像表示
1 2 3 4 5 | $file = $path . 'sample.jpg' ; $enc_data = file_get_contents ( $file ); $dec_data = CryptionUtil::decData( $enc_data ); header( 'Content-type: image/jpeg' ); echo $dec_data ; |
PHPはわかりやすくて好き