A way to filter sha1 would be so:
function isSHA1($sha1) {
return (bool) preg_match('/^[0-9a-f]{40}$/i', $sha1);
}
If you are using PDO for example, you can do so:
$dbh = new PDO("mysql:host=localhost;dbname=seubanco", $user, $pass);
try {
if (!isset($_POST['usuario'])) {
throw new PDOException('Informe o nome de usuário!');
}
if (!isset($_POST['senha'])) {
throw new PDOException('Informe a senha!');
}
if (!isUser($_POST['usuario'])) {
//aqui você cria um método para tratar o usuário
throw new PDOException('Informa um usuário válido!');
}
if (!isSHA1($_POST['senha'])) {
throw new PDOException('A senha informada é inválida!');
}
$stmt = $dbh->prepare("
INSERT INTO usuarios (usuario, senha)
VALUES (:user,:pass)
");
$usuario = $_POST['usuario'];
$senha = $_POST['senha'];
$stmt->bindParam(':user', $usuario);
$stmt->bindParam(':pass', $senha);
$stmt->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
But there’s no need to validate sha1 for such a case, as the user will enter a normal password, and then it will be converted to sha1:
$dbh = new PDO("mysql:host=localhost;dbname=seubanco", $user, $pass);
try {
if (!isset($_POST['usuario'])) {
throw new PDOException('Informe o nome de usuário!');
}
if (!isset($_POST['senha'])) {
throw new PDOException('Informe a senha!');
}
if (!isUser($_POST['usuario'])) {
//aqui você cria um método para tratar o usuário
throw new PDOException('Informa um usuário válido!');
}
$stmt = $dbh->prepare("
INSERT INTO usuarios (usuario, senha)
VALUES (:user,:pass)
");
$usuario = $_POST['usuario'];
//convertendo a senha para sha1
$senha = sha1($_POST['senha']);
$stmt->bindParam(':user', $usuario);
$stmt->bindParam(':pass', $senha);
$stmt->execute();
} catch(PDOException $e) {
echo $e->getMessage();
}
OBS: I do not recommend using hash with sha1()
and neither md5()
, although they are safe, as long as you include a token
together with the password, both have collision failure: In this question, he talks more about the subject
A good alternative to password is the use of password_rash.
http://answall.com/questions/3864/como-prevenir-inje%C3%A7%C3%a3o-de-c%C3%b3digo-sql-no-meu-c%C3%b3digo-php/3869
– gustavox
I didn’t understand how regex solved the sql Injection problem, it seems that it created another.
– rray
Using
PDO
, ormysqi_*
just create a placeholder type to inject a valid SQL, do not see why treat the data withpreg_replace()
. example in PDO:insert into tabela (senha) values (:senha_string)
and in mysqi:insert into tabela (senha) values(?)
.– Ivan Ferrer
@Ivanferrer already do it with mysqli
– Bia
But you agree that it is impossible to do sql Injection when vc declares the field
$stmt->bindParam(':senha', $senha);
the only thing you will do is validate the format, but you will never be injected a query that damages your system with it.– Ivan Ferrer