如何使用 servlet 将密码散列和加盐到 mysql 数据库中? [英] How do I hash and salt a password into mysql database using a servlet?

查看:62
本文介绍了如何使用 servlet 将密码散列和加盐到 mysql 数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我从我的 servlet 中得到的

Here is what I have from my servlet

Random random = new Random();
String salt = Integer.toString(random.nextInt(1000000000 - 1 + 1) + 1);

String sql = "insert into users (user_name, salt, password) "
                + "values (?, ?, ?)";

        c = DriverManager.getConnection( url, username, password );
        PreparedStatement pstmt = c.prepareStatement( sql );
        pstmt.setString( 1, userName );
        pstmt.setString( 2, salt);
        pstmt.setString( 3, "SHA2(CONCAT('" +password1+ "', "+ salt +"), 256)");

用户名和密码的值正确存储在服务器上,但密码不是.对于给定的值,它存储为以下 SHA2(CONCAT('edf', 733903552), 256).

The values for the username and password are stored correctly on the server but the password is not. It is stored as the following SHA2(CONCAT('edf', 733903552), 256) for the given values.

我假设 SHA2 和 CONCAT 函数没有生效,已经玩了一段时间,但不知道为什么.

I am assuming the SHA2 and CONCAT function are not taking effect, been playing around with it for a while and can't figure out why.

推荐答案

这是一个字符串文字被传递,这就是被存储的内容.考虑:

It's a string literal being passed, and that's what's being stored. Consider:

 String foo = "SHA2(CONCAT('" +password1+ "', "+ salt +"), 256)";
 pstmt.setString( 3, foo );

foo 的值是在 SQL 语句中作为值传入的.

The value of foo is what gets passed in as a value in the SQL statement.

MySQL 不会将该字符串的任何内容视为 SQL 文本...它只是一个字符串.(这是我们想要的行为.准备好的语句和绑定占位符的一大好处是防止 SQL 注入,即防止 被解释为 SQL 的一部分.)

MySQL doesn't see any of the contents of that string as SQL text... it's just a string. (This is behavior that we want. One of the big benefits of prepared statements and bind placeholders is preventing SQL injection, that is, preventing values from being interpreted as part of the SQL.)

如果您希望 CONCATSHA2 函数作为 MySQL 函数执行,则它们需要成为 SQL 文本的一部分.仅传入(作为值)password1salt.

If you want the CONCAT and SHA2 functions executed as MySQL functions, those need to be part of the SQL text. Pass in (as values) just password1 and salt.

像这样:

 String sql = "insert into users (user_name, salt, password)"
            + " values (?, ?, SHA2(CONCAT( ? , ? ),256) )";


 pstmt.setString( 1, userName );
 pstmt.setString( 2, salt );
 pstmt.setString( 3, password1 );
 pstmt.setString( 4, salt );

这篇关于如何使用 servlet 将密码散列和加盐到 mysql 数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆