effectra/security

Effectra 安全包。

v1.0.0 2023-06-19 17:37 UTC

This package is auto-updated.

Last update: 2024-09-18 12:49:23 UTC


README

Effectra\Security 是一个 PHP 库,提供如哈希、密码管理、CSRF 令牌处理和令牌生成等安全相关功能。

特性

  • 哈希:使用各种算法安全地哈希数据。
  • 密码管理:生成和验证哈希密码。
  • CSRF 保护:为 Web 应用程序生成和验证 CSRF 令牌。
  • 令牌生成:创建和解码 JSON Web Tokens (JWT)。

要求

  • PHP 7.0 或更高版本

安装

您可以通过 Composer 安装 Effectra\Security 库。在项目目录中运行以下命令:

composer require effectra/security

使用方法

哈希

Effectra\Security\Hash 类提供了使用 HMAC 算法哈希数据的函数。

示例用法

use Effectra\Security\Hash;

$data = 'Hello, World!';
$key = 'secret-key';

$hash = Hash::set($data, $key);
echo "Hashed value: " . $hash;

密码管理

Effectra\Security\Hash 类还包括用于安全地管理密码的函数。

示例用法

use Effectra\Security\Hash;

$password = 'password123';

$hashedPassword = Hash::setPassword($password);
echo "Hashed password: " . $hashedPassword;

$isPasswordValid = Hash::verifyPassword($password, $hashedPassword);
if ($isPasswordValid) {
    echo "Password is valid.";
} else {
    echo "Password is invalid.";
}

CSRF 保护

Effectra\Security\Csrf 类提供了生成和验证 CSRF 令牌的功能。

示例用法

use Effectra\Security\Csrf;
use Effectra\Session\Session; // Replace with your own session implementation

// Initialize the CSRF class with a session instance
$session = new Session();
$csrf = new Csrf($session);

// Generate and insert a CSRF token in your HTML form
$html = '<form>';
$html .= $csrf->insertHiddenToken();
$html .= '<input type="submit" value="Submit">';
$html .= '</form>';

echo $html;

// Validate the CSRF token on form submission
if ($csrf->validate()) {
    echo "CSRF token is valid.";
} else {
    echo "CSRF token is invalid.";
}

令牌生成

Effectra\Security\Token 类允许您生成和解码 JSON Web Tokens (JWT)。

示例用法

use Effectra\Security\Token;

$data = ['user_id' => 123];

$config = (object) [
    'issued_at' => time(),
    'expirationTime' => time() + 3600, // Expiration time 1 hour from now
    'issuer' => 'example.com',
    'key' => 'your-secret-key'
];

$token = new Token();
$encodedToken = $token->set($data, $config);
echo "Encoded token: " . $encodedToken;

$decodedToken = $token->get($encodedToken, $config);
echo "Decoded token: ";
print_r($decodedToken);

贡献

欢迎贡献!请随时在 GitHub 仓库 上提交错误报告、功能请求或拉取请求。

许可证

Effectra\Security 采用 MIT 许可证

鸣谢

Effectra\Security 由 Effectra 开发和维护。