このガイドでは、暗号化と復号化を実装する方法について説明します。 Laravel モデルの機密データ。これらの手順に従うことで、次のことが可能になります データベースに保存する前にデータを保護し、データベースに保存するときに復号化します。 取得中です。
前提条件
- Laravel: Laravel プロジェクトを使用していることを確認してください。
- 暗号化キー: Laravel は .env ファイルに APP_KEY を自動的に生成します。このキーは、Laravel の暗号化サービスによって使用されます。
ステップ 1: モデルで暗号化をセットアップする
モデルでは、Laravel の encrypt() 関数と decrypt() 関数を使用して、指定されたフィールドの暗号化と復号化を自動的に処理します。
Doctor Model
暗号化および復号化メソッドを使用して Doctor モデルを作成または更新します。 first_name、last_name、email、mobile などのフィールドは、データベースに保存する前に暗号化されます。
<?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() を使用してデータを暗号化してから、
- ゲッター メソッド: 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); }}
説明
- register メソッド: 受信リクエストを検証し、新しい医師レコードを作成し、モデルの暗号化メソッドにより、first_name、last_name、電子メール、携帯電話などのフィールドを自動的に暗号化します。
- 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();});
注: 暗号化された値は大幅に長くなる可能性があるため、暗号化フィールドにはプレーンテキスト値よりも TEXT が優先されます。
ステップ 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 サイトの他の関連記事を参照してください。

laravelMigrationSstreamLedinedAtabaseManagementionbyAllowingsCheMachAngESTOBEDEDINPHPCODE

Laravelの最新バージョンを見つけるには、公式Webサイトlaravel.comにアクセスして、右上隅の「ドキュメント」ボタンをクリックするか、Composersコマンド「Composershowlaravel/Framework | Grepversions」を使用できます。更新され続けると、プロジェクトのセキュリティとパフォーマンスの向上に役立ちますが、既存のプロジェクトへの影響を考慮する必要があります。

Youは、loredupdateTotheTothESTLARAVERVERSIONFORPERFORMANCEIMPROVEMENTS、強化セキュリティ、NewFeatures、BetterCommunitySupport、およびLong-Termmantenance.1)パフォーマンス:laravel9'seloquentormizationsenhanceapplicationspeed.2)laravel8introducedbetter

YuouMessupAmigrationInlaravel、1)RollBackTheMigrationS'PhpartisanMigrate:rollback'ifit'sthelastone、Or'phpartisanMigrate:reset'forall;

ToBoostperformanceInthElatestlaravelversion、FollowTheSteps:1)useredisisporcaching toefroveresponsetimeSandatedatubaseload.2)最適化されたabaseasequerieswitheageringtopreventn 1 queryissues.3)rutecachinginpoductionsospeeduprowtereSolution。

LARAVEL10INTRODUCESSERALKEYFEATURESTENHANCEWEBDEVELOPMENT.1)LAZYCOLLECTIONSSALLECTIONSSALLOWECTIONSALLOWESPICIENTPROCESSINGOFLAREDATASETSWITHOUTLECORDSINTOMEMORY.2)The'Make:Model and-Migration'ArtisAncommandSimplifiesingModElsandmigrations.3)Integration

はい、laravelmigrationsworthusing.itsimplifiesdatabaseschemamamanagement、entancescollaboration、およびprovidesversioncontrol.useitfortructured、efficientdevelopment。


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

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

WebStorm Mac版
便利なJavaScript開発ツール

MinGW - Minimalist GNU for Windows
このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。

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