設定Configuration
Laravelの暗号化機能を使う前に、config/app.phpファイルのkeyオプションへ32文字のランダム文字列を確実に設定してください。この値をしっかりと設定しないとLaravelにより暗号化される値は安全ではありません。Before using Laravel's encrypter, you should set the key option of your config/app.php configuration file to a 32 character, random string. If this value is not properly set, all values encrypted by Laravel will be insecure.
基本的な使用法Basic Usage
値の暗号化Encrypting A Value
値を暗号化するには、Cryptファサードが使用できます。暗号化にはいつでもOpenSSLが使用され、AES-256-CBCアルゴリズムが行われます。さらに全暗号化値は変更を検出するためMACを使い署名されます。You may encrypt a value using the Crypt facade[/docs/{{version}}/facades]. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC) to detect any modifications to the encrypted string.
たとえば、secretを暗号化するためにencryptメソッドを使い、Eloquentモデルへ保存してみましょう。For example, we may use the encrypt method to encrypt a secret and store it on an Eloquent model[/docs/{{version}}/eloquent]:
<?php
namespace App\Http\Controllers;
use Crypt;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* ユーザーの秘密のメッセージを保存
*
* @param Request $request
* @param int $id
* @return Response
*/
public function storeSecret(Request $request, $id)
{
$user = User::findOrFail($id);
$user->fill([
'secret' => Crypt::encrypt($request->secret)
])->save();
}
}
注意: 暗号化の過程で、値は「シリアライズ」されています。これにより、オブジェクトや配列も暗号化できます。そのため、PHP以外のクライアントが暗号化された値を受け取る場合、そのデータを非シリアライズする必要があるでしょう。Note: Encrypted values are passed through
serializeduring encryption, which allows for "encryption" of objects and arrays. Thus, non-PHP clients receiving encrypted values will need tounserializethe data.
値の復号Decrypting A Value
当然ながらCryptファサードのdecryptメソッドを使えば、暗号値を解読(復号)できます。MACが無効な場合など、その値が正しくない時はIlluminate\Contracts\Encryption\DecryptExceptionが投げられます。Of course, you may decrypt values using the decrypt method on the Crypt facade. If the value can not be properly decrypted, such as when the MAC is invalid, an Illuminate\Contracts\Encryption\DecryptException will be thrown:
use Illuminate\Contracts\Encryption\DecryptException;
try {
$decrypted = Crypt::decrypt($encryptedValue);
} catch (DecryptException $e) {
//
}