本指南介紹了如何在 laravel 模型中實(shí)現(xiàn)敏感數(shù)據(jù)的加密和解密。通過(guò)執(zhí)行以下步驟,您可以在將數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)之前保護(hù)數(shù)據(jù)并在檢索數(shù)據(jù)時(shí)對(duì)其進(jìn)行解密。
?先決條件
- Laravel:確保您使用的是 Laravel 項(xiàng)目。
- 加密密鑰:Laravel 在 .env 文件中自動(dòng)生成 APP_KEY。該密鑰由 Laravel 的加密服務(wù)使用。
? ?第 1 步:在模型中設(shè)置加密
在模型中,我們將使用 Laravel 的 encrypt() 和 decrypt() 函數(shù)自動(dòng)處理指定字段的加密和解密。
? ?Doctor模型
使用加密和解密方法創(chuàng)建或更新Doctor模型。我們將在將名字、姓氏、電子郵件和手機(jī)等字段保存到數(shù)據(jù)庫(kù)之前對(duì)其進(jìn)行加密。
<?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); }}
?????說(shuō)明
- Setter 方法:使用 set{AttributeName }Attribute() 在數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫(kù)之前對(duì)數(shù)據(jù)進(jìn)行加密。
- Getter 方法:從數(shù)據(jù)庫(kù)檢索數(shù)據(jù)時(shí),使用 get{AttributeName}Attribute() 解密。
第 2 步:數(shù)據(jù)存儲(chǔ)和檢索的控制器
在控制器中,您可以處理驗(yàn)證并調(diào)用模型的 直接加密屬性,無(wú)需額外加密/解密 步驟。
? ?????DoctorController
DoctorController 通過(guò)驗(yàn)證來(lái)處理注冊(cè) 輸入數(shù)據(jù),通過(guò)模型對(duì)其進(jìn)行加密,并將其保存在數(shù)據(jù)庫(kù)中。 獲取醫(yī)生數(shù)據(jù)時(shí),會(huì)自動(dòng)解密 敏感字段。
<?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); }}
? ?說(shuō)明
- register 方法:驗(yàn)證傳入的請(qǐng)求,創(chuàng)建新的醫(yī)生記錄,并根據(jù)模型的加密方法自動(dòng)加密名字、姓氏、電子郵件和手機(jī)等字段。
- show 方法:通過(guò) ID 檢索醫(yī)生記錄。這 模型的 getter 方法之前會(huì)自動(dòng)解密敏感字段 返回?cái)?shù)據(jù)。
? ?步驟 3:數(shù)據(jù)庫(kù)配置
確保敏感數(shù)據(jù)的 doctor 表列的長(zhǎng)度足以處理加密數(shù)據(jù)(通常為 TEXT 或 LONGTEXT)。
遷移設(shè)置示例:
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();});
注意:由于加密值可能比明文長(zhǎng)得多值,加密字段首選文本。
? ?步驟 4:處理解密異常
為了增強(qiáng)錯(cuò)誤處理,請(qǐng)將解密邏輯包裝在模型 getter 的 try-catch 塊中:
public function getFirstNameAttribute($value){ try { return decrypt($value); } catch (DecryptException $e) { return null; // Or handle the error as needed }}
? ?附加說(shuō)明
- 環(huán)境安全:確保 APP_KEY 安全地存儲(chǔ)在 .env 文件中。此密鑰對(duì)于加密/解密至關(guān)重要。
- 數(shù)據(jù)備份:如果數(shù)據(jù)完整性至關(guān)重要,請(qǐng)確保您有備份機(jī)制,因?yàn)闆](méi)有正確的 APP_KEY,加密數(shù)據(jù)將無(wú)法恢復(fù)。
? ?摘要
- 模型加密:存儲(chǔ)前使用setter方法加密數(shù)據(jù),檢索時(shí)使用getter方法解密。
- 控制器邏輯:控制器可以直接處理加密字段,無(wú)需額外的加密代碼.
- 數(shù)據(jù)庫(kù)配置:使用 TEXT 或 LONGTEXT 列作為加密字段。
- 安全注意事項(xiàng):保護(hù)您的 APP_KEY 并在 getter 中使用異常處理來(lái)處理解密錯(cuò)誤。