このガイドでは、Laravel モデルで機密データの暗号化と復号化を実装する方法について説明します。次の手順を実行すると、データベースに保存する前にデータを保護し、データを取得するときに復号化できます。
前提条件
- Laravel: Laravel プロジェクトを使用していることを確認してください。
- 暗号化キー: Laravel は .env ファイルに APP_KEY を自動的に生成します。このキーは、Laravel の暗号化サービスによって使用されます。
ステップ 1: モデルで暗号化を設定する
モデルでは、Laravel の encrypt() 関数と decrypt() 関数を使用して、指定されたフィールドの暗号化と復号化を自動的に処理します。
Doctor Model
暗号化および復号化メソッドを使用して Doctor モデルを作成または更新します。姓、名、電子メール、携帯電話などのフィールドは、データベースに保存する前に暗号化されます。
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use IlluminateSupportFacadesCrypt;class Doctor extends Model{ protected $fillable = [ 'first_name', 'last_name', 'email', 'mobile', 'hashed_email', 'password' ]; // Automatically encrypt attributes when setting them public function setFirstNameAttribute($value) { $this->attributes['first_name'] = encrypt($value); } public function setLastNameAttribute($value) { $this->attributes['last_name'] = encrypt($value); } public function setEmailAttribute($value) { $this->attributes['email'] = encrypt($value); } public function setMobileAttribute($value) { $this->attributes['mobile'] = encrypt($value); } // Automatically decrypt attributes when getting them public function getFirstNameAttribute($value) { return decrypt($value); } public function getLastNameAttribute($value) { return decrypt($value); } public function getEmailAttribute($value) { return decrypt($value); } public function getMobileAttribute($value) { return decrypt($value); }}
説明
- Setter メソッド: set{AttributeName }Attribute() を使用して、データベースに保存する前にデータを暗号化します。
- Getter メソッド: データベースからデータを取得するときに、get{AttributeName}Attribute() を使用して復号化します。
ステップ 2: データの保存と取得のためのコントローラー
コントローラーでは検証を処理し、モデルの呼び出しを行うことができます。 追加の暗号化/復号化を行わずに属性を直接暗号化します ステップ。
DoctorController
DoctorController は検証を通じて登録を処理します
データを入力し、モデルを通じて暗号化し、データベースに保存します。
医師データを取得すると自動的に復号化されます
敏感な分野。
<?phpnamespace AppHttpControllers;use IlluminateHttpRequest;use AppModelsDoctor;use IlluminateSupportFacadesHash;class DoctorController extends Controller{ public function register(Request $request) { // Validate the incoming request $validatedData = $request->validate([ 'first_name' => 'required|string|max:255', 'last_name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:doctors,email', 'mobile' => 'required|string|size:10|unique:doctors,mobile', 'password' => 'required|string|min:8|confirmed', ]); // Hash the email to ensure uniqueness $hashedEmail = hash('sha256', $validatedData['email']); // Create a new doctor record (model will handle encryption) $doctor = Doctor::create([ 'first_name' => $validatedData['first_name'], 'last_name' => $validatedData['last_name'], 'email' => $validatedData['email'], 'hashed_email' => $hashedEmail, 'mobile' => $validatedData['mobile'], 'password' => Hash::make($validatedData['password']), ]); return response()->json([ 'message' => 'Doctor registered successfully', 'doctor' => $doctor ], 201); } public function show($id) { // Fetch the doctor record (model will decrypt the data automatically) $doctor = Doctor::findOrFail($id); return response()->json($doctor); }}
説明
- 登録メソッド: 受信リクエストを確認し、新しい医師の記録を作成し、モデルの暗号化方法に基づいて名、姓、電子メール、携帯電話などのフィールドを自動的に暗号化します。
- show メソッド: ID によって医師の記録を取得します。これ 機密フィールドは、モデルのゲッター メソッドの前に自動的に復号化されます。 データを返します。
ステップ 3: データベース構成
機密データのドクター テーブル列が、暗号化されたデータ (通常は TEXT または LONGTEXT) を処理するのに十分な長さであることを確認します。
移行設定の例:
Schema::create('doctors', function (Blueprint $table) { $table->id(); $table->text('first_name'); $table->text('last_name'); $table->text('email'); $table->string('hashed_email')->unique(); // SHA-256 hashed email $table->text('mobile'); $table->string('password'); $table->timestamps();});
注: 暗号化された値はプレーン テキストよりもはるかに長くなる可能性があるため、暗号化フィールドにはテキストが優先されます。 。
ステップ 4: 復号例外を処理する
エラー処理を強化するには、モデルゲッターの try-catch ブロックに復号ロジックをラップします:
<?phpnamespace AppModels;use IlluminateDatabaseEloquentModel;use IlluminateSupportFacadesCrypt;class Doctor extends Model{ protected $fillable = [ 'first_name', 'last_name', 'email', 'mobile', 'hashed_email', 'password' ]; // Automatically encrypt attributes when setting them public function setFirstNameAttribute($value) { $this->attributes['first_name'] = encrypt($value); } public function setLastNameAttribute($value) { $this->attributes['last_name'] = encrypt($value); } public function setEmailAttribute($value) { $this->attributes['email'] = encrypt($value); } public function setMobileAttribute($value) { $this->attributes['mobile'] = encrypt($value); } // Automatically decrypt attributes when getting them public function getFirstNameAttribute($value) { return decrypt($value); } public function getLastNameAttribute($value) { return decrypt($value); } public function getEmailAttribute($value) { return decrypt($value); } public function getMobileAttribute($value) { return decrypt($value); }}
追加の注意事項
- 環境セキュリティ: APP_KEY が .env ファイルに安全に保存されていることを確認してください。このキーは暗号化/復号化に必須です。
- データのバックアップ: データの整合性が重要な場合は、適切な APP_KEY がないと暗号化されたデータを回復できなくなるため、バックアップ メカニズムが用意されていることを確認してください。
概要
- モデルの暗号化: 保存前にデータを暗号化するには setter メソッドを使用し、取得中に復号化するには getter メソッドを使用します。
- コントローラー ロジック: コントローラーは、暗号化コードを追加せずに暗号化されたフィールドを直接処理できます。
- データベース構成: TEXT 列または LONGTEXT 列を暗号化フィールドとして使用します。
- セキュリティに関する注意: APP_KEY を保護し、ゲッターで例外処理を使用して復号化エラーを処理します。
以上がLaravelでのデータの暗号化と復号化の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

反応、vue、andangularcanbe veintedated withlaravelbyfollowingspecificsetupSteps.1)forReact:instruectusinglaravelui、setUpComponentsInapp.js.2)forvue:uselaravel'sbuilt-invuesuptort、futureinapp.3)

Taskmanagementtoolsareessentialforeffectiveremoteprojectmanagementbyprioritizingtasksandtrackingprogress.1)UsetoolslikeTrelloandAsanatosetprioritieswithlabelsortags.2)EmploytoolslikeJiraandMonday.comforvisualtrackingwithGanttchartsandprogressbars.3)K

laravel10EnhancesperformAnceTheveralkeyfeatures.1)ItintroduceSquerybuilderCachinucedatedatabaseload.2)itoptimizeseLoquentModelloadingwithlazingproxies.3)itimprovesRoutingWithineSystem.4)itemproveStingwithingingSystem.4)

最高のフルスタックのLaravelアプリケーション展開戦略には、1。Zeroダウンタイム展開、2。ブルーグリーン展開、3。連続展開、4。Canaryリリースが含まれます。 1.ゼロダウンタイムデプロイメントは、EnvoyまたはDeployerを使用して展開プロセスを自動化して、更新時にアプリケーションを利用できるようにします。 2。ブルーとグリーンの展開により、2つの環境を維持し、迅速なロールバックを可能にすることにより、ダウンタイムの展開が可能になります。 3.継続的な展開GithubactionsまたはGitlabci/CDを使用して、展開プロセス全体を自動化します。 4。nginx構成を通じてカナリーがリリースされ、パフォーマンスの最適化と迅速なロールバックを確保するために、新しいバージョンをユーザーに徐々に宣伝します。

ToscalealAravelApplicationively、Focusondatabasesharding、Caching、Loadbalancing、andMicroservices.1)databaseShardingTodistributedataacrossMultipledatabase.2)uselaraval'scachingsmultedistestemedisemememememememedtededatedatab

ToovercomcomcommunicationbarriersindistributedTeams、使用:1)VideoCallsForface-to-faceInteraction、2)setClearResponsetimeExpectations、3)ChooseaprateCommunicationSoools、4)CreateAmCommunicationGuide、and5)

laravelbladeEnhancesFrontendTemplatinginfull stackprojectsbyofferingcleansyntaxandpowerfulfeatures.1)itallows foreasyvariabledisplayandcontrolstructures.2)bladeSupportscreating andReusing components、

laravelisidealforfull-stackapplicationsduetoitseLegantyntax、包括的なセコスシステム、およびパワーフルフィーチュア


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境
