本指南解釋如何實現加密和解密 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中文網其他相關文章!

Laravel通過簡化Web開發過程和提供強大功能脫穎而出。其優勢包括:1)簡潔的語法和強大的ORM系統,2)高效的路由和認證系統,3)豐富的第三方庫支持,使得開發者能專注於編寫優雅的代碼並提高開發效率。

laravelispredminandermanthandermanthandermanthandermanthermanderframework,設計Forserver-SideLogic,databasemagement,andapideplupment,thryitalsosupportsfortfortsfrontenddevelopmentwithbladeTemplates。

Laravel和Python在性能和可擴展性方面的表現各有優劣。 Laravel通過異步處理和隊列系統提升性能,但受PHP限制在高並發時可能有瓶頸;Python利用異步框架和強大的庫生態系統表現出色,但在多線程環境下受GIL影響。

Laravel適合團隊熟悉PHP且需功能豐富的項目,Python框架則視項目需求而定。 1.Laravel提供優雅語法和豐富功能,適合需要快速開發和靈活性的項目。 2.Django適合複雜應用,因其“電池包含”理念。 3.Flask適用於快速原型和小型項目,提供極大靈活性。

Laravel可以用於前端開發。 1)使用Blade模板引擎生成HTML。 2)集成Vite管理前端資源。 3)構建SPA、PWA或靜態網站。 4)結合路由、中間件和EloquentORM創建完整Web應用。

PHP和Laravel可用於構建高效的服務器端應用。 1.PHP是開源腳本語言,適用於Web開發。 2.Laravel提供路由、控制器、EloquentORM、Blade模板引擎等功能,簡化開發。 3.通過緩存、代碼優化和安全措施,提升應用性能和安全性。 4.測試和部署策略確保應用穩定運行。

Laravel和Python在學習曲線和易用性上的表現各有優劣。 Laravel適合快速開發Web應用,學習曲線相對平緩,但掌握高級功能需時間;Python語法簡潔,學習曲線平緩,但動態類型系統需謹慎。

Laravel在後端開發中的優勢包括:1)優雅的語法和EloquentORM簡化了開發流程;2)豐富的生態系統和活躍的社區支持;3)提高了開發效率和代碼質量。 Laravel的設計讓開發者能夠更高效地進行開發,並通過其強大的功能和工具提升代碼質量。


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Linux新版
SublimeText3 Linux最新版

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

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

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。