这是我的服务层,包括加密功能。
class profileService{
public function passEncrypt($userarray){
$password->setPassword($userarray['password']);
$plaintext = 'My secret message 1234';
$password = $password;
$method = 'aes-256-cbc';
// Must be exact 32 chars (256 bit)
$password = substr(hash('sha256', $password, true), 0, 32);
echo "Password:" . $password . "n";
// IV must be exact 16 chars (128 bit)
$iv = chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0) . chr(0x0);
// av3DYGLkwBsErphcyYp+imUW4QKs19hUnFyyYcXwURU=
$encrypted = base64_encode(openssl_encrypt($plaintext, $method, $password, OPENSSL_RAW_DATA, $iv));
return $encrypted;
// My secret message 1234
//$decrypted = openssl_decrypt(base64_decode($encrypted), $method, $password, OPENSSL_RAW_DATA, $iv);
echo 'plaintext=' . $plaintext . "n";
echo 'cipher=' . $method . "n";
echo 'encrypted to: ' . $encrypted . "n";
// echo 'decrypted to: ' . $decrypted . "nn";
}
}
这是我调用加密函数的DAO层
$profile = new profileService();
$pass_password= $profile->passEncrypt($userarray);
try {
$conn = $connection;
// our SQL statements
$Pass_user_id = $conn->query("SELECT MAX(id) FROM tb_user")->fetchColumn();
echo "User Last Id from User Table" . $Pass_user_id;
if (!$Pass_user_id) {
die('Could not query:' . mysql_error());
} else {
$sql="INSERT INTO tb_password ( user_id, email,password, status)
VALUES ('$Pass_user_id', '$pass_email','$pass_password','$pass_status' )";
$conn->exec($sql);
}
return 1;
}catch (PDOException $e ) {
/* if ($conn->isTransactionActive()) // this function does NOT exist
$conn->rollBack(); */
echo $e;
throw $e;
}
你可能想看看钠。它是添加到PHP的新扩展,基本上为一流的加密功能提供了一个现代接口。
在你的代码中,你自己做很多事情,比如构造一个初始化向量。这是你真正想要正确处理的事情类型,所以使用 PHP 内置功能通常是一种更安全的选择。特别是考虑到每次加密某些内容时,IV都应该是唯一的 - 因此您的代码暴露了对密码学应该如何工作的致命缺乏理解。我强烈建议你坚持使用库,而不是尝试自己实现这些相当复杂的概念。
请参阅:http://php.net/manual/en/book.sodium.php并且:https://paragonie.com/book/pecl-libsodium/read/04-secretkey-crypto.md#crypto-secretbox(来自PHP的钠积分的作者(