Skip to content

安全、验证码与上传

这一组能力覆盖 AES/RSA 加解密、密码传输、验证码和上传文件处理。

AES 与 RSA

配置文件 config/crypt.php 包含:

  • key:AES key,要求 16 字节。
  • iv:AES IV,要求 16 字节。
  • private_key:RSA 私钥。
  • public_key:RSA 公钥。

使用门面:

php
use Pin\Support\Facades\Aes;
use Pin\Support\Facades\Rsa;

$cipher = Aes::encrypt('payload');
$plain = Aes::decrypt($cipher);

$encrypted = Rsa::encrypt('payload');
$decrypted = Rsa::decrypt($encrypted);

生产环境应覆盖默认密钥,避免使用包内示例密钥。

密码传输

Pin\Password\Password 的流程是:

  1. 前端明文密码先做 strtoupper(md5(strtoupper($plain)))
  2. 再用 AES 加密作为请求密码。
  3. 后端 decodeFromRequest() 解密并校验 32 位大写格式。
  4. 存储时使用 Hash::make($encodedPassword.$salt)

示例:

php
use Pin\Support\Facades\Password;

$requestPassword = Password::encodeToRequest('secret');
$encoded = Password::decodeFromRequest($requestPassword);

$hash = Password::hash($encoded, $salt);
$ok = Password::check($encoded, $salt, $hash);

验证规则:

php
use Pin\Password\PasswordRule;

'password' => ['required', new PasswordRule()],

PasswordRule 包含长度、空白字符、重复字符、连续字符和组合复杂度校验。

验证码

内置路由由 CaptchaServiceProvider 根据配置注册:

路由说明
GET /api/captcha生成验证码
GET /api/captcha/rules获取可用规则

使用门面:

php
use Pin\Support\Facades\Captcha;

$captcha = Captcha::generate(rule: null, dark: false);

Captcha::validate($payload);
$result = Captcha::verify($payload);

payload 格式为:

text
input.encoded

其中 input 是用户输入,encoded 是服务端生成的 token。

配置重点:

php
'config' => [
    'width' => null,
    'height' => null,
    'angle' => 40,
    'font' => null,
    'font_size' => 16,
    'expires' => 300,
],

'routes' => [
    'enabled' => true,
],

'cache_enabled' => env('CAPTCHA_CACHE_ENABLED', true),

启用缓存后,验证码只允许检验一次。

上传规则

Pin\Upload\Rules\Upload 校验上传文件大小、扩展名和 MIME 类型。

php
use Pin\Upload\Rules\Upload;

'avatar' => [
    'required',
    (new Upload())
        ->disk('public')
        ->max('2M')
        ->extensions(['jpg', 'png', 'webp']),
],

通过校验后,UploadedFile::validated() 会将增强后的上传对象写入 request attributes:

php
use Pin\Upload\UploadedFile;

$file = UploadedFile::items($request->file('avatar'));
$path = $file->storeAs('avatars');

$file->thumb(width: 's');
$url = $file->url();

缩略图配置:

php
'thumb' => [
    's' => ['width' => 200, 'height' => null],
    'm' => ['width' => 500, 'height' => null],
    'l' => ['width' => 800, 'height' => null],
],

Base64 文件

php
use Pin\Upload\Base64File;

$file = new Base64File($base64, name: 'avatar');

构造时会创建临时文件,并可通过 request attribute base64file.avatar 取回。