SQL query in java with single quote

后端 未结 2 1465
梦毁少年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.

    0 讨论(0)
  • 2021-01-07 10:02

    Example of prepared queries:

    /*
     * Some code
     */
    String strSQL = "select md5(concat(md5(?),?))"
    try(PreparedStatement ps = conn.prepareStatement(strSQL)) {
        ps.setString(1, password);
        ps.setString(2, pwdSalt);
        try(ResultSet rs = ps.executeQuery()) {
            rs.first();
            // Do whatever you need to do
        } catch(SQLException e) {
            // ...
        }
    } catch(SQLException e) {
        // ...
    }
    
    /*
     * More code
     */
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题