怎样使用php添加token来防止csrf攻击?

For security code, please don’t generate your tokens this way: $token = md5(uniqid(rand(), TRUE));

rand() is predictable
uniqid() only adds up to 29 bits of entropy
md5() doesn’t add entropy, it just mixes it deterministically

Try this out:

Generating a CSRF Token
PHP 7
session_start();
if (empty($_SESSION[‘token’])) {
$_SESSION[‘token’] = bin2hex(random_bytes(32));
}
$token = $_SESSION[‘token’];
Sidenote: One of my employer’s open source projects is an initiative to backport random_bytes() and random_int() into PHP 5 projects. It’s MIT licensed and available on Github and Composer as paragonie/random_compat.

PHP 5.3+ (or with ext-mcrypt)
session_start();
if (empty($_SESSION[‘token’])) {
if (function_exists(‘mcrypt_create_iv’)) {
$_SESSION[‘token’] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
} else {
$_SESSION[‘token’] = bin2hex(openssl_random_pseudo_bytes(32));
}
}
$token = $_SESSION[‘token’];

Verifying the CSRF Token
Don’t just use == or even ===, use hash_equals() (PHP 5.6+ only, but available to earlier versions with the hash-compat library).

if (!empty(KaTeX parse error: Expected '}', got 'EOF' at end of input: …f (hash_equals(_SESSION[‘token’], $_POST[‘token’])) {
// Proceed to process the form data
} else {
// Log this as a warning and keep an eye on these attempts
}
}

地址:http://stackoverflow.com/questions/6287903/how-to-properly-add-csrf-token-using-php

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值