/** * Generate and save a one-time-token for a form. Used to protect against * CSRF attacks. * * @param string $name * Name of the form to generate a token for. * * @param integer $ttl * How long the token should be valid in seconds. * * @return string * The token to supply with the form data. */ public static function set($name, $ttl = 3600) { $token = phpsecRand::str(32); /* Save the token to the cahce. */ phpsecCache::cacheSet('token-' . $name, $token, $ttl); return $token; }
/** * Generate a one-time-password (OTP). The password is only valid for a given time, * and must be delivered to the user instantly. The password is also only valid * for the current session. * * @param string $action * The action to generate a OTP for. This should be as specific as possible. * Used to ensure that the OTP is used for the intended action. * * @param array $data * Optional array of data that belongs to $action. Used to ensure that the action * is performed with the same data as when the OTP was generated. * * @param integer $length * OTP length. * * @param integer $ttl * Time to live for the OTP. In seconds. * * @return string * One time password that should be delivered to the user by for example email or SMS. * */ public static function generate($action, $data = '', $length = 6, $ttl = 480) { $pw = phpsecRand::str($length); $otp['pw'] = phpsecHash::create($pw); if ($data !== null) { $otp['data'] = phpsecHash::create(serialize($data)); } else { $otp['data'] = $data; } phpsecCache::cacheSet('otp-' . $action, $otp, $ttl); return $pw; }