'Alter login password with SQL statement doesn't work using Java PreparedStatement

I want to change the password of a Microsoft SQL Server User with the following SQL statement over JDBC (documentation):

ALTER LOGIN username WITH PASSWORD = '<newpassword>'

Constructing this statement with Java String concatenation is no option, because SQL injection would be possible:

String statement = "ALTER LOGIN username WITH PASSWORD = '" + newPassword + "'";

To circumvent this problem, I want to use a Java PreparedStatement:

// ... open JDBC connection "connection" ... 

String sql = "ALTER LOGIN username WITH PASSWORD = ?";

try (PreparedStatement statement = connection.prepareStatement(sql))
{
    statement.setString(1, newPassword);

    statement.execute();
}

When this code is executed, the following Exception occurs:

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '@P0'.

Is there a way to make this work, or are there any alternatives to change a user's password?



Solution 1:[1]

I solved the problem by first generating the hash of the password and then altering the login by passing the hash instead of the plaintext password:

// ... open JDBC connection "connection" ... 

String sql = "SELECT PWDENCRYPT(?)";

String hash;

try (PreparedStatement statement = connection.prepareStatement(sql))
{
    statement.setString(1, newPassword);

    ResultSet rs = statement.executeQuery();

    rs.next();

    hash = rs.getString(1);
}

try (Statement statement = connection.createStatement())
{
    sql = "ALTER LOGIN username WITH PASSWORD = 0x" + hash + " HASHED";

    statement.execute(sql);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matthias Boehm