1. Go to this page and download the library: Download xgrug/laravel-gm-crypto library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Xgrug\LaravelGmCrypto\GmCryptoManager;
class UserController extends Controller
{
public function __construct(
private GmCryptoManager $crypto
) {}
public function store(Request $request)
{
$encryptedData = $this->crypto->sm4Encrypt($request->sensitive_data);
User::create([
'data' => $encryptedData
]);
}
}
use Illuminate\Database\Eloquent\Model;
use Xgrug\LaravelGmCrypto\Facades\GmCrypto;
class User extends Model
{
// 自动加密
public function setPhoneAttribute($value)
{
$this->attributes['phone'] = GmCrypto::sm4Encrypt($value);
}
// 自动解密
public function getPhoneAttribute($value)
{
return GmCrypto::sm4Decrypt($value);
}
}