本指南介紹如何在 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中文網其他相關文章!

React,vue,andangularCanBeintegratedWithLaravelByFollowingSpecificetUpSteps.1)forreact:installReactusingLaravelui,setUpComponentsInapp.js.js.js.js.2)forvue:uselaravel'sbuilt'sbuilt'sbuilt invuesupport,configureinapp.js.3)forangular forangular setuplare setulare sereptery sereptry and parkuly sereftery secparroughtery secparroughtery secparroughtery

taskManagementsToolSareEssentialForefectiverMototeprojectManagementbyPrioritizingTaskSandTrackingProgress.1)USETOOLSLIKETRELLOANDASANATASANATOSETPRIORITIONTAGS.2)

Laravel10enhancesPerformancEthroughSeveralKeyKeyFeatures.1)itintroducesquereBuilderCachingTordorcachingTordOuctedSataBaseload.2)itoptimiesseloizeseloquentmodelloAdingwithlazyproxies.3)

最佳的全棧Laravel應用部署策略包括:1.零停機部署,2.藍綠部署,3.持續部署,4.金絲雀發布。 1.零停機部署使用Envoy或Deployer自動化部署過程,確保應用在更新時保持可用。 2.藍綠部署通過維護兩個環境實現無停機部署,並允許快速回滾。 3.持續部署通過GitHubActions或GitLabCI/CD自動化整個部署流程。 4.金絲雀發布通過Nginx配置,將新版本逐步推廣給用戶,確保性能優化和快速回滾。

toscalealaravelApplication有效,焦點databaseSharding,緩存,負載平衡和microservices.1)實現DataBasEshardingTodistaCripedataCrossmultipledataBasesForimProvesforimPrevperformance.2)uselaravel'scachingsystemystemystemystemywithredsormememememememcachedtebachedtebab

doovercomecommunicationbarriersIndistributedTeams,使用:1)VideoCallSforface-to-Faceinteraction,2)setClearresponsEtimepections,3)chooseappropropropraproproprapropropriatecommunicationTools,4)CreatseateAteAteAteamCommunicationGuide和5)建立PemersonalBoundariestAriestOpeopReventBreventBurniationBurnication.the

laravelbladeenhancesfrontendtemplatinginflatinginflationll-stackprojectsbyferingCleanSyntaxandaxandpoperfelfulfeatures.1)itallowsforeasyvariableasyvariabledisplayandControlstructures.2)bladesuportsuportsuportscreatingingingingingingingingingingangingandredreingscomponents components components components,aidinginmanagingcomplexuis.3)

laravelisidealforll-stackapplicationsduetoitselegantsyntax,complastissionecosystem和perperatedfulfeatures.1)useeloquentormforintuivelbackenddatamanipulation,butavoidn 1queryissues.2)


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

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

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版
視覺化網頁開發工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境