重要:あなたが持っている場合を除き、非常に特定のユースケースを、暗号化しないパスワードを行い、代わりにパスワードのハッシュアルゴリズムを使用します。サーバーサイドアプリケーションでパスワードを暗号化すると誰かが言うとき、彼らは知らされていないか、危険なシステム設計を説明しています。パスワードを安全に保存することは、暗号化とはまったく別の問題です。
知らされる。安全なシステムを設計します。
PHPでのポータブルデータ暗号化
PHP 5.4以降を使用していて、自分で暗号化モジュールを作成したくない場合は、認証された暗号化を提供する既存のライブラリを使用することをお勧めします。私がリンクしたライブラリは、PHPが提供するものにのみ依存しており、少数のセキュリティ研究者によって定期的にレビューされています。(私も含まれます。)
あなたの移植性の目標がPECL拡張機能の要求を妨げない場合、あなたや私がPHPで書くことができるものよりもlibsodiumを強くお勧めします。
アップデート(2016-06-12): PECL拡張機能をインストールしなくても、sodium_compatを使用して、同じ暗号libsodiumオファーを使用できるようになりました。
暗号工学を試してみたい場合は、このまま読み進めてください。
まず、時間をかけて、認証されていない暗号化の危険性と暗号の破滅の原則を学ぶ必要があります。
- 暗号化されたデータは、悪意のあるユーザーによって改ざんされる可能性があります。
- 暗号化されたデータを認証することで、改ざんを防ぎます。
- 暗号化されていないデータを認証しても、改ざんを防ぐことはできません。
暗号化と復号化
PHPでの暗号化は実際には簡単です(これから使用openssl_encrypt()しopenssl_decrypt()、情報の暗号化方法についていくつかの決定を行っopenssl_get_cipher_methods()たら、システムでサポートされている方法のリストを参照してください。最良の選択はCTRモードのAESです:
- aes-128-ctr
- aes-192-ctr
- aes-256-ctr
現在、AESキーサイズが心配すべき重要な問題であると信じる理由はありません(256ビットモードでのキースケジューリングが不適切なため、これより大きくすることはおそらくあまり好ましくありません)。
注:放棄されたものであり、セキュリティに影響を与える可能性のあるパッチされていないバグがあるため、使用していませんmcrypt。これらの理由により、他のPHP開発者にも回避することをお勧めします。
OpenSSLを使用した単純な暗号化/復号化ラッパー
class UnsafeCrypto
{
    const METHOD = 'aes-256-ctr';
    /**
     * Encrypts (but does not authenticate) a message
     * 
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded 
     * @return string (raw binary)
     */
    public static function encrypt($message, $key, $encode = false)
    {
        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = openssl_random_pseudo_bytes($nonceSize);
        $ciphertext = openssl_encrypt(
            $message,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );
        // Now let's pack the IV and the ciphertext together
        // Naively, we can just concatenate
        if ($encode) {
            return base64_encode($nonce.$ciphertext);
        }
        return $nonce.$ciphertext;
    }
    /**
     * Decrypts (but does not verify) a message
     * 
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string
     */
    public static function decrypt($message, $key, $encoded = false)
    {
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }
        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = mb_substr($message, 0, $nonceSize, '8bit');
        $ciphertext = mb_substr($message, $nonceSize, null, '8bit');
        $plaintext = openssl_decrypt(
            $ciphertext,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );
        return $plaintext;
    }
}
使用例
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = UnsafeCrypto::encrypt($message, $key);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key);
var_dump($encrypted, $decrypted);
デモ:https : //3v4l.org/jl7qR
上記の単純な暗号ライブラリはまだ安全に使用できません。暗号文を認証し、復号する前に検証する必要があります。
注:デフォルトでUnsafeCrypto::encrypt()は、生のバイナリ文字列を返します。バイナリセーフ形式(base64エンコード)で保存する必要がある場合は、次のように呼び出します。
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = UnsafeCrypto::encrypt($message, $key, true);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key, true);
var_dump($encrypted, $decrypted);
デモ:http : //3v4l.org/f5K93
単純な認証ラッパー
class SaferCrypto extends UnsafeCrypto
{
    const HASH_ALGO = 'sha256';
    /**
     * Encrypts then MACs a message
     * 
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded string
     * @return string (raw binary)
     */
    public static function encrypt($message, $key, $encode = false)
    {
        list($encKey, $authKey) = self::splitKeys($key);
        // Pass to UnsafeCrypto::encrypt
        $ciphertext = parent::encrypt($message, $encKey);
        // Calculate a MAC of the IV and ciphertext
        $mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);
        if ($encode) {
            return base64_encode($mac.$ciphertext);
        }
        // Prepend MAC to the ciphertext and return to caller
        return $mac.$ciphertext;
    }
    /**
     * Decrypts a message (after verifying integrity)
     * 
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string (raw binary)
     */
    public static function decrypt($message, $key, $encoded = false)
    {
        list($encKey, $authKey) = self::splitKeys($key);
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }
        // Hash Size -- in case HASH_ALGO is changed
        $hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
        $mac = mb_substr($message, 0, $hs, '8bit');
        $ciphertext = mb_substr($message, $hs, null, '8bit');
        $calculated = hash_hmac(
            self::HASH_ALGO,
            $ciphertext,
            $authKey,
            true
        );
        if (!self::hashEquals($mac, $calculated)) {
            throw new Exception('Encryption failure');
        }
        // Pass to UnsafeCrypto::decrypt
        $plaintext = parent::decrypt($ciphertext, $encKey);
        return $plaintext;
    }
    /**
     * Splits a key into two separate keys; one for encryption
     * and the other for authenticaiton
     * 
     * @param string $masterKey (raw binary)
     * @return array (two raw binary strings)
     */
    protected static function splitKeys($masterKey)
    {
        // You really want to implement HKDF here instead!
        return [
            hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
            hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
        ];
    }
    /**
     * Compare two strings without leaking timing information
     * 
     * @param string $a
     * @param string $b
     * @ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
     * @return boolean
     */
    protected static function hashEquals($a, $b)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($a, $b);
        }
        $nonce = openssl_random_pseudo_bytes(32);
        return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
    }
}
使用例
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = SaferCrypto::encrypt($message, $key);
$decrypted = SaferCrypto::decrypt($encrypted, $key);
var_dump($encrypted, $decrypted);
デモ:rawバイナリ、base64エンコード
このSaferCryptoライブラリを本番環境で使用したい場合、または同じ概念を独自に実装したい場合は、常駐の暗号技術者にセカンドオピニオンを求める前に連絡することを強くお勧めします。彼らは私が気づいていないかもしれない間違いについてあなたに伝えることができるでしょう。
評判の良い暗号ライブラリを使用する方がはるかによいでしょう。