/**
  * Change the current password method
  *
  * @param oldPass the former user password
  * @param newPass the new user password
  * @return true if the password has change, false otherwise
  */
 public boolean setPassword(String oldPass, String newPass) {
   if (authenticate(oldPass)) {
     this.hashPSWD = BCrypt.hashpw(newPass, BCrypt.gensalt(11));
     return true;
   }
   return false;
 }
  @Test
  public void checkPasswordTrueTest() {

    String encryptedPW = BCrypt.hashpw("testPW", BCrypt.gensalt());
    userRepository.addUser(new User("testEmail", encryptedPW, "testUser", "testRole"));

    userRepository.checkPassword("testEmail", "testPW");
  }
  @Test(expected = InvalidInputException.class)
  public void checkPasswordFalseTest() {

    String encryptedPW = BCrypt.hashpw("testPW", BCrypt.gensalt());
    userRepository.addUser(new User("testEmail", encryptedPW, "testUser", "testRole"));

    userRepository.checkPassword("testEmail", "testFalse");
  }
  /**
   * Build a new end user instance
   *
   * @param id the end user unique identifier
   * @param pswd the end user password
   * @param lastName the end user last name
   * @param firstName the end user first name
   * @param role the end user role in the smart home
   */
  public AppsgateEndUser(String id, String pswd, String lastName, String firstName, String role) {
    super();

    this.instanciationService = Executors.newScheduledThreadPool(1);

    this.id = id;
    this.hashPSWD = BCrypt.hashpw(pswd, BCrypt.gensalt(11));
    this.lastName = lastName;
    this.firstName = firstName;
    this.role = role;
  }
Example #5
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    String username = req.getParameter("username");
    String password = req.getParameter("password");

    HttpSession session = req.getSession(false);
    if (session != null && session.getAttribute("user") != null) {
      resp.sendRedirect(req.getContextPath() + "/home");
      return;
    }

    if (!userService.isUsernameAlreadyRegistered(username)) {
      req.setAttribute(
          "error",
          "Could not find user "
              + username
              + ". Check its spelling or register if you aren't registered yet.");
      req.getRequestDispatcher("/login.jsp").forward(req, resp);
    } else {
      User user = userService.getUser(username);
      if (!BCrypt.checkpw(password, user.getPassword())) {
        req.setAttribute(
            "error", "Could not sign you in. Please check your username and password.");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
      }
      // these are the droids we are looking for
      session = req.getSession(true); // creates a new session if no session available
      session.setAttribute("user", user);
      resp.sendRedirect(req.getContextPath() + "/home");
    }
  }
 @Override
 @Transactional(propagation = Propagation.REQUIRED)
 public void resetPassword(User user, String guid) {
   // TODO Auto-generated method stub
   try {
     log.info("in reset password service method");
     String hashed = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(12));
     user.setPassword(hashed);
     userDao.update(user);
     userDao.removeGuid(guid);
     log.info("In resetPassword to update and delete guid");
   } catch (DataAccessException e) {
     log.error("in resetPassword ", e);
     throw e;
   }
 }
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    List<GrantedAuthority> grantedAuths = new ArrayList<>();

    Session session;
    UserCredientials userCredentials = null;
    try {
      session = sf.openSession();
      Transaction tx = session.beginTransaction();

      Query query = session.createQuery("from UserCredientials where userName = :uname");
      query.setParameter("uname", name);
      userCredentials = (UserCredientials) query.list().get(0);

      tx.commit();
    } catch (Exception e) {
      System.out.println("Exception occured: " + e.getMessage());
    }

    if (userCredentials != null
        && name.equals(userCredentials.getUserName())
        && BCrypt.checkpw(password, userCredentials.getPasswordHash())) {
      grantedAuths.add(new SimpleGrantedAuthority(userCredentials.getRoles()));
    } else {
      throw new BadCredentialsException("Bad Credentials");
    }

    Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
    return auth;
  }
Example #8
0
 public static User authenticate(String email, String password) {
   User user = find.where().eq("email", email).findUnique();
   if (user != null && !BCrypt.checkpw(password, user.password)) {
     user = null;
   }
   return user;
 }
Example #9
0
  /**
   * Hash a password using the OpenBSD bcrypt scheme
   *
   * @param password the password to hash
   * @param salt the salt to hash with (perhaps generated using BCrypt.gensalt)
   * @return the hashed password
   */
  public static String hashpw(String password, String salt) {
    BCrypt B;
    String real_salt;
    byte passwordb[], saltb[], hashed[];
    char minor = (char) 0;
    int rounds, off = 0;
    StringBuffer rs = new StringBuffer();

    if (salt.charAt(0) != '$' || salt.charAt(1) != '2')
      throw new IllegalArgumentException("Invalid salt version");
    if (salt.charAt(2) == '$') off = 3;
    else {
      minor = salt.charAt(2);
      if (minor != 'a' || salt.charAt(3) != '$')
        throw new IllegalArgumentException("Invalid salt revision");
      off = 4;
    }

    // Extract number of rounds
    if (salt.charAt(off + 2) > '$') throw new IllegalArgumentException("Missing salt rounds");
    rounds = Integer.parseInt(salt.substring(off, off + 2));

    real_salt = salt.substring(off + 3, off + 25);
    try {
      passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
    } catch (UnsupportedEncodingException uee) {
      throw new AssertionError("UTF-8 is not supported");
    }

    saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);

    B = new BCrypt();
    hashed = B.crypt_raw(passwordb, saltb, rounds, (int[]) bf_crypt_ciphertext.clone());

    rs.append("$2");
    if (minor >= 'a') rs.append(minor);
    rs.append("$");
    if (rounds < 10) rs.append("0");
    if (rounds > 30) {
      throw new IllegalArgumentException("rounds exceeds maximum (30)");
    }
    rs.append(Integer.toString(rounds));
    rs.append("$");
    rs.append(encode_base64(saltb, saltb.length));
    rs.append(encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1));
    return rs.toString();
  }
 public static boolean isPasswordSame(String userPassword, String encryptedPassword) {
   if (userPassword == null) {
     return false;
   }
   if (encryptedPassword == null) {
     return false;
   }
   return BCrypt.checkpw(userPassword, encryptedPassword);
 }
Example #11
0
 // Calculate a hash given an input and hashed version
 private static boolean calculateMatches(final String input, final String hashed) {
   Boolean result = false;
   try {
     result = BCrypt.checkpw(input, hashed);
   } catch (IllegalArgumentException iae) {
     LOGGER.error("Failed to calculate hash for input password", iae);
   }
   return result;
 }
Example #12
0
  /**
   * Tries to authenticate user who is trying to log in. Hashes entered password for entered email,
   * and checks if provided combination exists in the database.
   *
   * @param email
   * @param password
   * @return
   */
  public static AppUser authenticate(String email, String password) {

    AppUser user = finder.where().eq("email", email.toString()).findUnique();

    if (user != null && BCrypt.checkpw(password, user.password)) {
      return user;
    } else {
      return null;
    }
  }
 public static boolean authenticate(String username, String password) {
   if (username.isEmpty() || password.isEmpty()) {
     return false;
   }
   User user = userDao.getUserByUsername(username);
   if (user == null) {
     return false;
   }
   String hashedPassword = BCrypt.hashpw(password, user.getSalt());
   return hashedPassword.equals(user.getHashedPassword());
 }
 private void generateSaltIfNeeded(Path saltFilePath, Path secretsPath) throws Exception {
   FileSystem fileSystem = FileSystem.get(saltFilePath.toUri(), getConf());
   if (!fileSystem.exists(saltFilePath)) {
     FSDataOutputStream outputStream = fileSystem.create(saltFilePath);
     BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
     int numSaltsToGenerate = getNumSecrets(secretsPath);
     System.out.printf("Generating %d salts\n", numSaltsToGenerate);
     for (int i = 0; i < numSaltsToGenerate; i++) {
       writer.write(BCrypt.gensalt());
       writer.newLine();
     }
     writer.close();
     outputStream.close();
   }
 }
  /**
   * Debug/Run me as a java application to try out the query before you build the client connection
   * Right Click on me > Hit Debug As > Java Application
   *
   * <p>Make sure you have a JDBC connector in your JVM classpath, or goto Build Path and add
   * external jar. You will need to change the JDBC connector path in the build path
   */
  public static void main(String[] args) {

    // This will test the query with out to many classes in the way

    String username = "******";
    String password = "******";
    int uid = 1;

    // Construct SQL query parameters.
    Person person;

    // Start SQL.
    SqlSession session = DBConst.SQL.openSession();
    PersonMapper mapper = session.getMapper(PersonMapper.class);

    try {
      // Test 1.
      person = new Person(username, password);
      person = mapper.searchPerson(person);
      System.out.println("searchPerson");
      System.out.println("uid = " + person.uid);
      System.out.println("email = " + person.email);
      System.out.println("username = "******"password = "******"lname = " + person.lname);
      System.out.println("fname = " + person.fname);
      System.out.println("----------------------------");
      if (BCrypt.checkpw(password, person.password)) {
        System.out.println("The Password matches!!");
      } else {
        System.out.println("Password wrong!!");
      }
      System.out.println();

      // Test 2.
      person = mapper.getPersonByUid(uid);
      System.out.println("getPersonByUid");
      System.out.println("uid = " + person.uid);
      System.out.println("email = " + person.email);
      System.out.println("username = "******"password = "******"lname = " + person.lname);
      System.out.println("fname = " + person.fname);
      System.out.println();
    } finally {
      session.close();
    }
  }
Example #16
0
 // todo Request Responde Card
 public boolean checkPassword(String name, String password) {
   String exist = "";
   String passwordFromDB = null;
   try {
     dbm.setConnectionBehavior(new MySQLServerConnectionBehavior());
     dbm.openConnection();
     ResultSet rs =
         dbm.ExecuteQueryResultSet("SELECT * from users where user_name='" + name + ";");
     while (rs.next()) {
       passwordFromDB = rs.getString("user_password");
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
   return BCrypt.checkpw(password, passwordFromDB);
 }
Example #17
0
  /**
   * Check if the username and password are correct
   *
   * @param username The username of the user
   * @param password The password in plaintext!
   * @return the user if found, null if not.
   * @throws InvalidParameterException If the username do not exist or it doesn't match with the
   *     password
   * @throws StorageException If there is an internal error while trying to fetch info from database
   */
  public static Users login(String username, String password)
      throws InvalidParameterException, StorageException {
    Session session = HibernateUtil.getSessionFactory().openSession();

    try {
      session.beginTransaction();

      Users u = new UsersDaoImpl(session).getElementByName(username);

      session.getTransaction().commit();
      session.close();

      if (u == null) throw new InvalidParameterException("El usuario ingresado no existe.");

      // Check that an unencrypted password matches one that has previously been hashed
      if (!BCrypt.checkpw(password, u.getPassword()))
        throw new InvalidParameterException("El usuario ingresado y la contraseña no coinciden.");

      return u;
    } catch (HibernateException e) {
      throw new StorageException("Error interno al intentar leer el usuario.");
    }
  }
Example #18
0
  /**
   * Check an user to see if he can connect to the server Only existing user with correct group can
   * login
   *
   * @return the response, send it to the client
   */
  public String checkAuth() {
    String authResult = new String();

    // Get user informations from database
    ResultSet result;
    try {
      this.preparedStatement.setString(1, this.pseudo);
      result = this.preparedStatement.executeQuery();
    } catch (Exception e) {
      authResult = "DATABASE_ERROR";
      LOGGER.error("Impossible de communiquer avec la base de donnée", e);
      Loki.setStatus(false);
      try {
        this.preparedStatement.close();
        this.conn.close();
      } catch (SQLException e1) {
        LOGGER.fatal("Impossible de fermer correctement la connexion avec MySQL", e1);
      }
      return authResult;
    }

    // We split hash and group id
    int groupId;
    String passwordHash;
    try {
      // No user ?
      if (!result.next()) {
        authResult = "BAD_PSEUDO";
        return authResult;
      }

      groupId = result.getInt(1);
      passwordHash = result.getString(2);
      result.close();
    } catch (Exception e) {
      authResult = "UNKNOW_ERROR";
      LOGGER.error("Erreur inconnue durant la vérification du login", e);
      try {
        this.preparedStatement.close();
        this.conn.close();
      } catch (SQLException e1) {
        LOGGER.fatal("Impossible de fermer correctement la connexion avec MySQL", e1);
      }
      return authResult;
    }

    // We check the groupId
    if (!checkGroup(groupId)) {
      authResult = "BAD_GROUP";
      return authResult;
    }

    // We check login
    // The hash use an unsupported algo, must re-login on the forum
    if (!passwordHash.contains("$2a$")) {
      authResult = "PASSWORD_ERROR";
      // We test if the password is correct
    } else if (BCrypt.checkpw(this.password, passwordHash)) {
      authResult = "OK";
    } else {
      authResult = "BAD_PASSWORD";
    }

    try {
      this.preparedStatement.close();
      this.conn.close();
    } catch (SQLException e) {
      LOGGER.fatal("Impossible de fermer correctement la connexion avec MySQL", e);
    }

    return authResult;
  }
Example #19
0
 public static boolean checkPwd(String candidatePassword, String hashedPassword) {
   return BCrypt.checkpw(candidatePassword, hashedPassword);
 }
  public static String generatePasswordHash(String userPassword) {

    return BCrypt.hashpw(userPassword, BCrypt.gensalt());
  }
Example #21
0
 public static String hashPwd(String password) {
   return BCrypt.hashpw(password, BCrypt.gensalt(12));
 }
Example #22
0
 private String createPassword(String password) {
   return BCrypt.hashpw(password, BCrypt.gensalt());
 }
 public String generateSalt() {
   return BCrypt.gensalt();
 }
 public boolean checkPassword(String passwordToCheck, String hashed) {
   return BCrypt.checkpw(passwordToCheck, hashed);
 }
 public String hashPassword(String password, String salt) {
   return BCrypt.hashpw(password, salt);
 }
Example #26
0
 /** Hashes user password. */
 public void hashPass() {
   this.password = BCrypt.hashpw(this.password, BCrypt.gensalt());
 }
 /** default constructor it just initialize the password hash with empty string hash */
 public AppsgateEndUser() {
   this.hashPSWD = BCrypt.hashpw("", BCrypt.gensalt(11));
   this.instanciationService = Executors.newScheduledThreadPool(1);
 }
Example #28
0
  private void performTask(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Map<String, String[]> parameterInfo = request.getParameterMap();
    String password = request.getParameter("senderpassword");
    String random = request.getParameter("random");

    System.err.println(password);
    System.err.println(random);

    // check if random is available in database
    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
      System.out.println(e);
    }

    try {
      Connection con =
          DriverManager.getConnection(
              "jdbc:mysql://localhost:3306/c9", Properties.username, Properties.password);

      String SQLfind = "SELECT userid from PasswordReset where random = ?";
      PreparedStatement statementFind = con.prepareStatement(SQLfind);
      statementFind.setString(1, random);
      ResultSet rsFind = statementFind.executeQuery();

      if (rsFind.next()) {
        System.err.println("found random");
        System.err.println(Integer.toString(rsFind.getInt("userid")));

        // update password
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        String SQL = "UPDATE Members SET pass=? where id=?";
        PreparedStatement statement = con.prepareStatement(SQL);
        statement.setString(1, hashed);
        statement.setInt(2, rsFind.getInt("userid"));
        statement.execute();

        // delete row in passwordreset table
        SQL = "DELETE FROM PasswordReset where random=?";
        statement = con.prepareStatement(SQL);
        statement.setString(1, random);
        statement.execute();

        // get the userid and set the session
        SQL = "SELECT email, first_name, last_name FROM Members where id=?";
        statement = con.prepareStatement(SQL);
        statement.setInt(1, rsFind.getInt("userid"));
        ResultSet rs = statement.executeQuery();

        if (rs.next()) {
          HttpSession session = request.getSession();
          session.setAttribute("userid", rs.getString("email"));
          session.setAttribute(
              "naam", rs.getString("first_name") + " " + rs.getString("last_name"));
        }

        response.sendRedirect("success.jsp");
        // request.getRequestDispatcher("/success.jsp").forward(request, response);
      } else {
        response.setStatus(500);
      }

    } catch (SQLException se) {
      System.err.println(se);
      response.setStatus(500);
    }
  }
Example #29
0
  public void onStart(Application app) {

    Logger.info("Application started");
    String uploadPath = Configuration.getUploadPath();
    File file = new File(uploadPath);
    if (!file.exists()) {
      try {
        if (!file.mkdir()) {
          System.out.println(file.getAbsolutePath());
        }
        ;
      } catch (Exception e) {
        e.printStackTrace();
        System.out.println(
            "Error while creating directory for server files, please check 'uploadPath' value in application.conf file");
        System.exit(-1);
      }
    } else {
      if (!file.canRead() || !file.canWrite()) {
        System.out.println(
            "Error: Server have no read and write access to "
                + uploadPath
                + ", please check 'uploadPath' value in application.conf file");
        System.exit(-1);
      }
    }

    // Checking existence of main directory
    String usersFilesDir = Configuration.getUploadPath();
    File applicationDir = new File(usersFilesDir + "/users/");
    if (!applicationDir.exists()) {
      Boolean createAppDir = applicationDir.mkdir();
      if (!createAppDir) {
        Logger.warn("Error while creating users directory");
        System.exit(-1);
      } else {
        Logger.info("Users directory created");
      }
    }

    if (Configuration.isApplyNewLimits()) {
      for (Account account : Account.findAll()) {
        account.setNewLimits();
      }
    }

    if (Configuration.isCreateDefaultUsers()) {
      UserService userService = new UserService(app);
      try {
        Integer nDefault = Configuration.getnDefaultUsers();
        String nameDefault = Configuration.getNameDefaultUser();
        for (int i = 1; i <= nDefault; i++) {
          String username = nameDefault + Integer.toString(i);
          String email = username + "@vdjviz.com";
          LocalUser localUser = LocalUser.find.byId(email);
          if (localUser == null) {
            Option<PasswordHasher> bcrypt = Registry.hashers().get("bcrypt");
            SocialUser socialUser =
                new SocialUser(
                    new IdentityId(email, "userpass"),
                    username,
                    username,
                    String.format("%s %s", username, username),
                    Option.apply(email),
                    null,
                    AuthenticationMethod.UserPassword(),
                    null,
                    null,
                    Some.apply(
                        new PasswordInfo(
                            "bcrypt", BCrypt.hashpw(username, BCrypt.gensalt()), null)));
            userService.doSave(socialUser);
          }
        }
      } catch (RuntimeException e) {
        Logger.error("Error while creating default users");
        e.printStackTrace();
      }
    }

    // Deleting empty files
    for (Account account : Account.findAll()) {
      for (UserFile userFile : account.getUserfiles()) {
        File fileDir = new File(userFile.getDirectoryPath());
        if (!fileDir.exists() || !userFile.checkExist()) {
          UserFile.deleteFile(userFile);
          Logger.of("user." + account.getUserName())
              .warn(
                  "Deleted empty file "
                      + userFile.getFileName()
                      + " for user : "******"user." + account.getUserName())
                              .info("File " + userFile.getFileName() + " was deleted");
                        }
                      }
                    }
                  }
                }
              },
              Akka.system().dispatcher());
    }
  }
 /**
  * Authenticate the end user password
  *
  * @param candidatepswd the password to test
  * @return true if the password correspond to this end user password, false otherwise
  */
 public boolean authenticate(String candidatepswd) {
   return BCrypt.checkpw(candidatepswd, hashPSWD);
 }