Laravel 中的資料加密與解密
本指南解釋如何實現加密和解密 Laravel 模型中的敏感資料。透過執行以下步驟,您可以 在將資料儲存到資料庫之前對其進行保護,並在儲存時對其進行解密 正在檢索它。
先決條件
- Laravel:確保您使用的是 Laravel 專案。
- 加密金鑰:Laravel 在 .env 檔案中自動產生 APP_KEY。此金鑰由 Laravel 的加密服務使用。
第 1 步:在模型中設定加密
在模型中,我們將使用 Laravel 的 encrypt() 和 decrypt() 函數自動處理指定欄位的加密和解密。
Doctor模型
使用加密和解密方法建立或更新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); }}
說明
- register 方法:驗證傳入的請求,建立新的醫生記錄,並根據模型的加密方法自動加密名字、姓氏、電子郵件和手機等欄位。
- show 方法:透過 ID 檢索醫師記錄。這 模型的 getter 方法之前會自動解密敏感字段 返回數據。
步驟 3:資料庫設定
確保敏感資料的 doctor 表格列的長度足以處理加密資料(通常為 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:處理解密異常
為了增強錯誤處理,請將解密邏輯包裝在模型 getter 的 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 並在 getter 中使用異常處理來處理解密錯誤。
以上是Laravel 中的資料加密與解密的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Laravel 是一款 PHP 框架,用於輕鬆構建 Web 應用程序。它提供一系列強大的功能,包括:安裝: 使用 Composer 全局安裝 Laravel CLI,並在項目目錄中創建應用程序。路由: 在 routes/web.php 中定義 URL 和處理函數之間的關係。視圖: 在 resources/views 中創建視圖以呈現應用程序的界面。數據庫集成: 提供與 MySQL 等數據庫的開箱即用集成,並使用遷移來創建和修改表。模型和控制器: 模型表示數據庫實體,控制器處理 HTTP 請求。

在使用CraftCMS開發網站時,常常會遇到資源文件緩存的問題,特別是當你頻繁更新CSS和JavaScript文件時,舊版本的文件可能仍然被瀏覽器緩存,導致用戶無法及時看到最新的更改。這個問題不僅影響用戶體驗,還會增加開發和調試的難度。最近,我在項目中遇到了類似的困擾,經過一番探索,我找到了wiejeben/craft-laravel-mix這個插件,它完美地解決了我的緩存問題。

Laravel 提供了一個全面的 Auth 框架,用於實現用戶登錄功能,包括:定義用戶模型(Eloquent 模型)創建登錄表單(Blade 模板引擎)編寫登錄控制器(繼承 Auth\LoginController)驗證登錄請求(Auth::attempt)登錄成功後重定向(redirect)考慮安全因素:哈希密碼、防 CSRF 保護、速率限制和安全標頭。此外,Auth 框架還提供重置密碼、註冊和驗證電子郵件等功能。詳情請參閱 Laravel 文檔:https://laravel.com/doc

想要學習 Laravel 框架,但苦於沒有資源或經濟壓力?本文為你提供了免費學習 Laravel 的途徑,教你如何利用網絡平台、文檔和社區論壇等資源,從入門到掌握,為你的 PHP 開發之旅奠定堅實基礎。

文章摘要:本文提供了詳細分步說明,指導讀者如何輕鬆安裝 Laravel 框架。 Laravel 是一個功能強大的 PHP 框架,它 упростил 和加快了 web 應用程序的開發過程。本教程涵蓋了從系統要求到配置數據庫和設置路由等各個方面的安裝過程。通過遵循這些步驟,讀者可以快速高效地為他們的 Laravel 項目打下堅實的基礎。

在面向初学者的 Laravel 框架版本选择指南中,本文深入探討了 Laravel 的版本差異,旨在協助初學者在眾多版本之間做出明智的選擇。我們將重點介紹每個版本的關鍵特徵、比較它們的優缺點,並提供有用的建議,幫助新手根據他們的技能水準和項目需求挑選最合適的 Laravel 版本。對於初學者來說,選擇一個合適的 Laravel 版本至關重要,因為它可以顯著影響他們的學習曲線和整體開發體驗。

Laravel框架內置了多種方法來方便地查看其版本號,滿足開發者的不同需求。本文將探討這些方法,包括使用Composer命令行工具、訪問.env文件或通過PHP代碼獲取版本信息。這些方法對於維護和管理Laravel應用程序的版本控制至關重要。

Laravel 和 ThinkPHP 都是流行的 PHP 框架,在開發中各有優缺點。本文將深入比較這兩者,重點介紹它們的架構、特性和性能差異,以幫助開發者根據其特定項目需求做出明智的選擇。
