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)

2025年全球十大加密貨幣交易所包括Binance、OKX、Gate.io、Coinbase、Kraken、Huobi、Bitfinex、KuCoin、Bittrex和Poloniex,均以高交易量和安全性著稱。

比特幣的價格在20,000到30,000美元之間。 1. 比特幣自2009年以來價格波動劇烈,2017年達到近20,000美元,2021年達到近60,000美元。 2. 價格受市場需求、供應量、宏觀經濟環境等因素影響。 3. 通過交易所、移動應用和網站可獲取實時價格。 4. 比特幣價格波動性大,受市場情緒和外部因素驅動。 5. 與傳統金融市場有一定關係,受全球股市、美元強弱等影響。 6. 長期趨勢看漲,但需謹慎評估風險。

全球十大加密貨幣交易平台包括Binance、OKX、Gate.io、Coinbase、Kraken、Huobi Global、Bitfinex、Bittrex、KuCoin和Poloniex,均提供多種交易方式和強大的安全措施。

目前排名前十的虛擬幣交易所:1.幣安,2. OKX,3. Gate.io,4。幣庫,5。海妖,6。火幣全球站,7.拜比特,8.庫幣,9.比特幣,10。比特戳。

Binance、OKX、gate.io等十大數字貨幣交易所完善系統、高效多元化交易和嚴密安全措施嚴重推崇。

使用C 中的chrono庫可以讓你更加精確地控制時間和時間間隔,讓我們來探討一下這個庫的魅力所在吧。 C 的chrono庫是標準庫的一部分,它提供了一種現代化的方式來處理時間和時間間隔。對於那些曾經飽受time.h和ctime折磨的程序員來說,chrono無疑是一個福音。它不僅提高了代碼的可讀性和可維護性,還提供了更高的精度和靈活性。讓我們從基礎開始,chrono庫主要包括以下幾個關鍵組件:std::chrono::system_clock:表示系統時鐘,用於獲取當前時間。 std::chron

在C 中處理高DPI顯示可以通過以下步驟實現:1)理解DPI和縮放,使用操作系統API獲取DPI信息並調整圖形輸出;2)處理跨平台兼容性,使用如SDL或Qt的跨平台圖形庫;3)進行性能優化,通過緩存、硬件加速和動態調整細節級別來提升性能;4)解決常見問題,如模糊文本和界面元素過小,通過正確應用DPI縮放來解決。

DMA在C 中是指DirectMemoryAccess,直接內存訪問技術,允許硬件設備直接與內存進行數據傳輸,不需要CPU干預。 1)DMA操作高度依賴於硬件設備和驅動程序,實現方式因係統而異。 2)直接訪問內存可能帶來安全風險,需確保代碼的正確性和安全性。 3)DMA可提高性能,但使用不當可能導致系統性能下降。通過實踐和學習,可以掌握DMA的使用技巧,在高速數據傳輸和實時信號處理等場景中發揮其最大效能。
