使用 where 子句获取加密数据

Fetch encrypted data using where clause

除了主键(id),我的整个数据库都是加密的。我需要使用 $email 变量获取电子邮件。

$encrypted=registermodel::select('email')->where('email','=',$email)->get();

你不能轻易 - 它已加密!您将不得不获取每条记录对其进行解密,然后比较明文

这是解决问题的正确方法https://www.sitepoint.com/how-to-search-on-securely-encrypted-database-fields/

下面是我尝试使用基于 CRC 的索引列

<?php

namespace App\ModelTraits;

use Illuminate\Support\Facades\Crypt;

/**
 * 
 */
trait EmailSigTrait
{

    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = Crypt::encryptString($value);
        $this->attributes['emailsig'] = Self::crcemail($value);
    }

    public function getEmailAttribute()
    {
        if(!isset($this->attributes['email'])){
            return;
        }

        $value = $this->attributes['email'];

        if (empty($value)) {
            return;
        }

        return strtolower(Crypt::decryptString($value));
    }

    static function crcemail($email)
    {
        $email = strtolower($email);

        // anonymise the email
        $name = str_before($email,'@');

        $anon = substr($name, 0, 1) .
                substr($name, strlen($name)/2,1) .
                substr($name, -1) .
                '@' . str_after($email, '@');

        return sprintf(crc32(strToLower($anon)));
    }

    protected function findByEmailSig($email, $model)
    {
        $email = strtolower($email);

        $candidates = $model::where('emailsig', $model::crcemail($email))->get();

        foreach ($candidates as $candidate) {
            if (strtolower($candidate->email) == $email) {
                return $candidate;
            }
        }
        return false;
    }

}

在具有加密电子邮件地址的模型中包含此特征。

为 'emailsig'

添加文本列

当您保存电子邮件字段时,会为部分电子邮件地址创建一个 crc 值,并对电子邮件进行加密。

检索电子邮件时解密

找到电子邮件时,它会计算用户要查找的 CRC,然后将其与为每个电子邮件地址存储的 CRC 值进行比较。因为可能有多个匹配项(多个具有相同 CRC 值的电子邮件),所以它会迭代可能的选择,直到找到正确的电子邮件。

根据您今天加密电子邮件的方式,您可能需要进行调整以适应。