inspirecz / security
安全包
v2.0.1
2022-04-21 13:26 UTC
Requires
- php: ^8.0
- ext-openssl: *
- nette/security: ^2|^3
Requires (Dev)
- mockery/mockery: 1.3.*
- phpunit/phpunit: ~9.0
- squizlabs/php_codesniffer: ^3.5
README
用于处理加密和解密密码的包。
要求
InspireCZ/Security 需要 PHP 8.0 或更高版本。
安装
安装 InspireCZ/Security 的最佳方式是使用 Composer
$ composer require inspirecz/security
使用
对称加密
使用密钥加密或解密所需数据。加密使用 AES-256-CTR 算法(密钥必须为 32 个字符)。
$hash = 'edb433bdd7c13851c7c68cb31a5acf33'; $symetric = new \Inspire\Security\Crypt\OpenSSLSymetricEncoderDecoder($hash); $plaintext = 'Hello world!'; $ciphertext = $symetric->encode($plaintext); echo $symetric->decode($ciphertext); // vystup: Hello world!
为了方便在项目中使用,可以将对称加密注册为服务(例如,使用构造函数注入)
config.neon
parameters: crypt: symetrickey: 'edb433bdd7c13851c7c68cb31a5acf33' service: - TestService cryptService: \Inspire\Security\Crypt\OpenSSLSymetricEncoderDecoder(%crypt.symetricKey%)
TestService.php
class TestService { /** @var \Inspire\Security\Crypt\OpenSSLSymetricEncoderDecoder */ private $cryptService; /** * @param \Inspire\Security\Crypt\OpenSSLSymetricEncoderDecoder $cryptService */ public function __construct(\Inspire\Security\Crypt\OpenSSLSymetricEncoderDecoder $cryptService) { $this->cryptService = $cryptService; } /** * @param string $text * * @return string */ public function useCrypt(string $text): string { return $this->cryptService->encode($text); } }
使用公钥/私钥加密
该包包含两个类,用于使用公钥或私钥加密或解密。基本特点是,使用公钥加密的数据只能使用私钥解密,反之亦然。如果私钥与密码相关联,则可以使用密码。
限制:数据的最大长度取决于使用的密钥。对于 RSA 256 位,限制为 245 个字符
$publicCrypt = \Inspire\Security\Crypt\OpenSSLPublicKeyCrypt::fromFile('public_key.pem'); $privateCrypt = \Inspire\Security\Crypt\OpenSSLPrivateKeyCrypt::fromFile('private_key.pem', 'passwordForKey'); $plaintext = 'Secret message for private key'; $ciphertext = $publicCrypt->encrypt($plaintext); echo $privateCrypt->decrypt($ciphertext); // vystup: Secret message for private key $plaintext = 'Secret message for public key'; $ciphertext = $privateCrypt->encrypt($plaintext); echo $publicCrypt->decrypt($ciphertext); // vystup: Secret message for public key
可以通过 new 关键字创建 KeyCrypt 对象,作为构造函数参数直接传递密钥内容,或者可以使用辅助静态方法 fromFile。它期望作为参数传入密钥文件的路径,并返回新的 crypt 对象实例。
从密码生成哈希并验证其正确性
$generator = new \Inspire\Security\Password\BCryptPasswordHashGenerator(); $hash = $generator->generate('my-brutal-password'); if ($generator->verify('i-dont-know-my-password', $hash)) { echo 'OK'; } else { echo 'Try it again'; } // výstup: Try it again
生成随机令牌
$generator = new \Inspire\Security\Password\RandomTokenGenerator(); echo $generator->generate(); // výstup: edb433bdd7c13851c7c68cb31a5acf33
测试
$ vendor/bin/phpunit test
安全
如果发现任何安全漏洞,请通过电子邮件 support@inspire.cz 联系我们,而不是使用问题报告。