SQL query in java with single quote

后端 未结 2 1464
梦毁少年i
梦毁少年i 2021-01-07 09:02

I have a query that I want run in java:

SELECT md5(CONCAT(md5(\'{clear password}\') , \'{salt}\'));

Its for my application to connect and u

2条回答
  •  执念已碎
    2021-01-07 09:42

    If I follow your question, then you could do it with something like this -

    String sql = "select md5(CONCAT(md5(?), ?))";
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      ps = conn.prepareStatement(sql);
      ps.setString(1, password);
      ps.setString(2, pwdSalt);
      rs = ps.executeQuery();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    

    Another possible solution is to perform the hash and salt in Java -

    // A password hashing method.
    public static String hashPassword(String in, String salt) {
      try {
        MessageDigest md = MessageDigest.getInstance("MD5"); // <-- Or, SHA-256
        md.update(salt.getBytes());        // <-- Prepend salt.
        md.update(in.getBytes());
        // md.update(salt.getBytes());     // <-- Or, append salt.
    
        byte[] out = md.digest();
        return bytesToHex(out);            // <-- Return the Hex Hash.
      } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
      }
      return "";
    }
    
    private static String bytesToHex(byte[] byteArr) {  
      StringBuilder sb = new StringBuilder();   
      Formatter fmt = new Formatter(sb);  
      for (byte b : byteArr) {  
        fmt.format("%02x", b);  
      }  
      return sb.toString();
    }  
    

    Finally, I wouldn't use MD5 in 2014. SHA-256 would be my preference.

提交回复
热议问题