
使用 PHP 的最简单双向加密
背景
警告:避免使用这些方法加密密码;相反,采用密码哈希算法来安全存储密码。
PHP 中的可移植数据加密
当使用 PHP 5.4 或更高版本并希望代码可移植性时,请利用提供经过身份验证的加密的现有库。一旦您选择了加密方法,就可以使用 Openssl 方法,例如 openssl_encrypt() 和 openssl_decrypt()。
加密和解密
考虑使用高级加密标准 (AES)用于加密的 CTR 模式。此方法提供了安全性和性能之间的最佳平衡。请参阅 openssl_get_cipher_methods() 以获取支持的方法列表。
使用 OpenSSL 的简单加密/解密包装器
以下 PHP 类提供了使用 OpenSSL 的简单加密/解密包装器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | class UnsafeCrypto
{
const METHOD = 'aes-256-ctr' ;
public static function encrypt( $message , $key , $encode = false)
{
if ( $encode ) {
return base64_encode ( $nonce . $ciphertext );
}
return $nonce . $ciphertext ;
}
public static function decrypt( $message , $key , $encoded = false)
{
$plaintext = openssl_decrypt(
$ciphertext ,
self::METHOD,
$key ,
OPENSSL_RAW_DATA,
$nonce
);
return $plaintext ;
}
}
|
登录后复制
简单的身份验证包装器
为了增强安全性,实施身份验证以验证加密数据的完整性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | class SaferCrypto extends UnsafeCrypto
{
const HASH_ALGO = 'sha256' ;
public static function encrypt( $message , $key , $encode = false)
{
if ( $encode ) {
return base64_encode ( $mac . $ciphertext );
}
return $mac . $ciphertext ;
}
public static function decrypt( $message , $key , $encoded = false)
{
$calculated = hash_hmac(
self::HASH_ALGO,
$ciphertext ,
$authKey ,
true
);
if (!self::hashEquals( $mac , $calculated )) {
throw new Exception( 'Encryption failure' );
}
$plaintext = parent::decrypt( $ciphertext , $encKey );
return $plaintext ;
}
}
|
登录后复制
以上是如何在PHP中实现简单的双向加密和认证?的详细内容。更多信息请关注PHP中文网其他相关文章!