Code with Finding: |
class DatabaseAdmin {
public static int changePassword(Connection conn, String username, String pwdStore) {
int status = -1;
String fetchAnswer = "SELECT secanswer FROM main.users WHERE username = ?";
String query = "UPDATE main.users SET pwhash = ?, checksum = ? WHERE username = ?";
PreparedStatement answerStmt = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
try {
answerStmt = conn.prepareStatement(fetchAnswer);
answerStmt.setString(1, username);
rs = answerStmt.executeQuery();
if (rs.next()) {
String secA = SharedKeyCrypto.decrypt(rs.getString("secanswer"));
//recalculate the new hash to update this user's entry
//create checksum to add as 5th element
byte[] userBytes = username.getBytes("UTF8");
byte[] pwBytes = pwdStore.getBytes("UTF8");
byte[] ansBytes = secA.getBytes("UTF8");
byte[] toChecksum = new byte[userBytes.length + pwBytes.length + ansBytes.length];
System.arraycopy(userBytes, 0, toChecksum, 0, userBytes.length);
System.arraycopy(pwBytes, 0, toChecksum, userBytes.length, pwBytes.length);
System.arraycopy(ansBytes, 0, toChecksum, pwBytes.length + userBytes.length, ansBytes.length);
pstmt = conn.prepareStatement(query);
pstmt.setString(1, SharedKeyCrypto.encrypt(pwdStore));
pstmt.setString(2, CryptoUtil.encode(Hash.generateChecksum(toChecksum)));
pstmt.setString(3, username);
status = pstmt.executeUpdate();
}
else {
//this cannot happen, checked before function is entered
}
} catch (SQLException e) {
status = -1;
} catch (UnsupportedEncodingException e) {
//cannot happen
} finally {
DBManager.closeResultSet(rs);
DBManager.closeStatement(answerStmt);
DBManager.closePreparedStatement(pstmt);
}
return status;
}
}
|