inium/php-security-crypto

一个简单的AES和bcrypt模块封装类。

0.1.0 2020-04-14 08:29 UTC

This package is auto-updated.

Last update: 2024-09-14 18:09:49 UTC


README

PHP实现Bcrypt加密和验证,AES加密和解密。

概述

PHP实现的Bcrypt,AES加密及解密的类模块。以下功能已实现。

  • 使用Bcrypt进行hash加密及验证
  • 使用AES进行加密和解密

构成

本项目由以下内容组成。

Bcrypt

Bcrypt是一种单向hash加密方式。无法解密,只能验证加密字符串与给定字符串是否匹配。主要用于密码加密。

Bcrypt通过php提供的password_hashpassword_verify函数实现。

AES

本项目中的AES使用openssl系列函数进行字符串加密,以下方式可供使用。

  • 128bit: aes-128-cbc, aes-128-cfb, aes-128-ctr, aes-128-ofb
  • 192bit: aes-192-cbc, aes-192-cfb, aes-192-ctr, aes-192-ofb
  • 256bit: aes-256-cbc, aes-256-cfb, aes-256-ctr, aes-256-ofb

实现参考以下链接。

加密过程

  • 生成随机IV
  • 应用HMAC(基于散列的消息认证码)以验证加密字符串是否被篡改/修改
  • 根据用户选择对加密目标字符串进行gzip压缩
  • 最终加密字符串由base64编码的IV + HMAC + CipherText(加密字符串)组成

解密过程

  • 对加密字符串进行base64解码后,将IV,HMAC,CipherText(加密字符串)分离
  • 使用CipherText生成HMAC并与加密字符串中包含的HMAC进行比较,以验证是否被篡改
    • HMAC验证通过后执行解密。如果压缩,则执行解压后返回
    • HMAC验证失败时,通知CipherText(加密字符串)已被篡改。

使用方法

本项目在PHP 7.0及以上版本中实现。同时,在composer.json中设置为从PHP 7.0及以上版本开始使用。

安装

使用以下方法安装composer

composer require inium/php-security-crypto

Bcrypt hash加密及验证

hash加密

使用本项目的Bcrypt将密码转换为hash代码(加密)的过程如下。

<?php
$password = "${YOUR_PASSWORD}";

$bcrypt = new Inium\Security\Crypto\Bcrypt();

$hash = $bcrypt->hash($password);

echo $hash;

验证

使用本项目的Bcrypt验证密码的过程如下。

<?php
$hash = "${PASSWORD_HASH}";     // 암호화된 비밀번호
$password = "${YOUR_PASSWORD}"; // 본래 비밀번호

$bcrypt = new Inium\Security\Crypto\Bcrypt();

$verified = $bcrypt->verify($password, $hash);

if ($verified) {
  echo "Password verification success.";
}
else {
  echo "Password verification fail.";
}

AES加密及解密

加密Key

加密Key应使用以下大小创建并使用。

  • 128bit (AES-128-*): 16字节
  • 192bit (AES-192-*): 24字节
  • 256bit (AES-256-*): 32字节

加密

使用本项目的AES对明文进行加密的过程如下。

<?php
$plainText = "${YOUR_PLAIN_TEXT}";

$key = "${YOUR_AES_KEY}";
$cipherMethod = 'aes-256-cbc';
$useGzCompression = true;

// AES(string $key, string $cipherMethod = 'aes-256-cbc', bool $useGzCompression = false)
$aes = new Inium\Security\Crypto\AES($key, $cipherMethod, $useGzCompression);

$cipherText = $aes->encrypt($plainText);

echo $cipherText;

解密

使用本项目的AES对密文进行解密的过程如下。

<?php
$cipherText = "${YOUR_CIPHER_TEXT}";

$key = "${YOUR_AES_KEY}";
$cipherMethod = 'aes-256-cbc';
$useGzCompression = true;

$aes = new Inium\Security\Crypto\AES($key, $cipherMethod, $useGzCompression);

$plainText = $aes->decrypt($cipherText);

echo $plainText;

测试

使用PHPUnit在/tests目录下实现了TestCase。可以进行以下测试。

./vendor/bin/phpunit --testdox tests

许可证

MIT