7
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【PHP】データの暗号化・復号化

Last updated at Posted at 2020-12-24

PHPで動作するデータの暗号化・復号化のメモです。
通信時やDBのアクセス時などで使用します。

動作環境

PHP 7.3.11

プロトコル

AES-256-CBCを使用します。

#暗号化


    const AES_KEY = 'tekitou_key';
    const AES_IV= 'tekitou_iv';
    
    /**
     * 暗号化
     * @param string $data
     * @return string
     */
    function encrypt($data)
    {
        return $data === null ? null :
            openssl_encrypt($data, 'AES-256-CBC', AES_KEY, 0, AES_IV);
    }

#復号化


    const AES_KEY = 'tekitou_key';
    const AES_IV= 'tekitou_iv';

    /**
     * 復号化
     * @param string $data
     * @return string
     */
    function decrypt($data)
    {
        return $data === null ? null :
            openssl_decrypt($data, 'AES-256-CBC', AES_KEY, 0, AES_IV);
    }

#全体



<?php

    const AES_KEY = 'tekitou_key';
    const AES_IV= 'tekitou_iv';
        
    /**
     * 暗号化
     * @param string $data
     * @return string
     */
    function encrypt($data)
    {
        return $data === null ? null :
            openssl_encrypt($data, 'AES-256-CBC', AES_KEY, 0, AES_IV);
    }

    /**
     * 復号化
     * @param string $data
     * @return string
     */
    function decrypt($data)
    {
        return $data === null ? null :
            openssl_decrypt($data, 'AES-256-CBC', AES_KEY, 0, AES_IV);
    }

    //何かしらのデータ
    $value = 'nanikano_data';
    echo $value;

    //暗号化
    $encrypt_value = encrypt($value);
    echo $encrypt_value;

    //復号化
    $decrypt_value = decrypt($encrypt_value);
    echo $decrypt_value;
?>

#最後に
keyやivの情報はベタ書きせず、生成するメソッドや隠匿するメソッドを経由したほうが良いと思います。

7
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?