Hi guys ,

I have designed a form for users to create a login account . I found that passwords are MD5 protected .In my form i asked Firstname, lastname , email and password for account creation . Insert work very well but i am not being able to protect the password that has been entered . Password are stored in workflow variable named NewUserPassword .

My code is :

String password = "#variable.NewUserPassword#";
				String insertQuery = "INSERT INTO dir_user (id, username, firstName, lastName, password, email, active, timezone) values (?, ?, ?, ?, ?, ?, '1', '0')";
                PreparedStatement istmt = con.prepareStatement(insertQuery);
                istmt.setString(1, row.getProperty("UserEmail"));
                istmt.setString(2, row.getProperty("UserEmail"));
                istmt.setString(3, row.getProperty("UserFirstname"));
                istmt.setString(4, row.getProperty("UserLastname"));
                istmt.setString(5, here i need to md5 the password ??? ));
		istmt.setString(6, row.getProperty("UserEmail"));
                istmt.executeUpdate();

				//Setting role for this new user
    			String SqlSetRole = "INSERT INTO dir_user_role (roleId,userId) values ('ROLE_USER',?) ";
    			PreparedStatement statementAffectRole = con.prepareStatement(SqlSetRole);
				statementAffectRole.setString(1, row.getProperty("UserEmail"));
    			statementAffectRole.executeUpdate(); 

I also have this in my code :

public static String md5Base16(String content) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(content.getBytes());
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            String hex = Integer.toHexString((int) 0x00FF & b);
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString();
    } catch (Exception e) {}
    return "";
}

public static String md5(String content) {
    try {
        MessageDigest m = MessageDigest.getInstance("MD5");
        byte[] data = content.getBytes();
        m.update(data, 0, data.length);
        BigInteger i = new BigInteger(1, m.digest());
        return String.format("%1$032X", i);
    } catch (Exception ex) {}
    return "";
}

when in my sql command i do : md5('password') ; the insert work well with "password" as password . But i need to md5 a variable , i am not being able to put the correct syntax . Can anyone one give me the correct syntax ?

Thank you very much . Best .

  • No labels

3 Comments

  1. Example, this is the present code, simplified.

    String abc = "#variable.abc#";
    
    function renderValue(String a){
    return a + a;
    }
    
    System.out.println( renderValue(abc) );

    When the script runs, Joget will parse the hash variable, which we will get the following.

    String abc = "hello world";
    
    function renderValue(String a){
    return a + a;
    }
    
    System.out.println( renderValue(abc) );

    Thus, we will get the following print out.

    hello worldhello world

    In your coding, change accordingly, to...

    istmt.setString(5, md5(password) );
  2. Hi Walter ,

    Thank you for your answer , but i am having the following error :

    Sourced file: inline evaluation of: ``import org.joget.apps.app.service.*; import org.joget.apps.app.model.*; import o . . . '' : Error in method invocation: Static method format( java.lang.String, java.math.BigInteger ) not found in class'java.lang.String' : at Line: 162 : in file: inline evaluation of: ``import org.joget.apps.app.service.*; import org.joget.apps.app.model.*; import o . . . '' : String .format ( "%1$032X" , i )
    

    My complete code is below :

    import org.joget.apps.app.service.*;
    import org.joget.apps.app.model.*;
    import org.joget.apps.form.model.*;
    import org.joget.apps.form.service.*;
    import java.sql.*;
    import java.util.*;
    import org.joget.apps.form.lib.*;
    import org.apache.commons.collections.SequencedHashMap;
    import org.joget.commons.util.UuidGenerator;
    import java.math.BigInteger;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    public FormRowSet storeData() {
        normalStoring(element, rows, formData);
    
        //store only needed field by create new Form Row Set
        FormRow originalRow = rows.get(0);
    
        FormRowSet newRows = new FormRowSet();
        FormRow newRow = new FormRow();
    
        newRow.put("UserFirstname", originalRow.getProperty("UserFirstname"));
        newRow.put("UserLastname", originalRow.getProperty("UserLastname"));
        newRow.put("UserEmail", originalRow.getProperty("UserEmail"));
        //newRow.put("Password", originalRow.getProperty("Password"));
    	newRows.add(newRow);
    
        String id = "#currentUser.username#";
    
        //Store
        storeToOtherFormDataTable(element, newRows, formData, id);
        StoreUsingJDBC(element, newRows, formData, id);
    
        return rows;
    }
    
    //this function will put all the data gather from the element's childs to it's parent store binder
    public void normalStoring(Element element, FormRowSet rows, FormData formData) {
        if (rows != null && !rows.isEmpty()) {
            // find parent that have store binder
            Element parent = element.getParent();
            while (parent.getStoreBinder() == null && parent.getParent() != null) {
                parent = parent.getParent();
            }
    
            FormStoreBinder storeBinder = parent.getStoreBinder();
            if (storeBinder != null) {
                FormRowSet parentRows = formData.getStoreBinderData(storeBinder);
                FormRow currentRow = rows.get(0);
                if (parentRows != null && parentRows.size() == 1 && rows.size() == 1) {
                    FormRow parentRow = parentRows.get(0);
                    parentRow.putAll(currentRow);
                } else {
                    parentRows = new FormRowSet();
                    FormRow parentRow = new FormRow();
                    parentRow.putAll(currentRow);
                    parentRows.add(parentRow);
    
                    formData.setStoreBinderData(storeBinder, parentRows);
                }
            }
        }
    }
    
    //this function will store rows data to a form's data table
    public void storeToOtherFormDataTable(Element element, FormRowSet rows, FormData formData, String id) {
        AppService appService = (AppService) FormUtil.getApplicationContext().getBean("appService");
    
        String formId = "NewUser"; // the table of database is configured in the form with id "user"
        AppDefinition appDef = AppUtil.getCurrentAppDefinition();
    
        appService.storeFormData(appDef.getId(), appDef.getVersion().toString(), formId, rows, id);
    }
    
    //this function will store rows data to external source using JDBC
    public void StoreUsingJDBC(Element element, FormRowSet rows, FormData formData, String id) {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jwdb?characterEncoding=UTF-8", "root", "WEBmaster12044+-");
    
            if(!con.isClosed()){
                //manually handle insert and update by checking the data is exist or not
                String selectQuery = "SELECT username FROM dir_user WHERE username=?";
                PreparedStatement stmt = con.prepareStatement(selectQuery);
                stmt.setString(1, id);
                ResultSet rs = stmt.executeQuery();
    
                Boolean isExist = false;
                if (rs.next()) {
                    isExist = true;
                }
    
                FormRow row = rows.get(0);
    
                if (isExist) {
                    //String updateQuery = "UPDATE dir_user SET firstName = ?, lastName = ?, email = ? WHERE username = ?";
                    //PreparedStatement ustmt = con.prepareStatement(updateQuery);
                    //ustmt.setString(1, row.getProperty("firstName"));
                    //ustmt.setString(2, row.getProperty("lastName"));
                    //ustmt.setString(3, row.getProperty("email"));
                    //ustmt.setString(4, id);
                    //ustmt.executeUpdate();
    
                } else {
    
    
    
    				String password = "#variable.NewUserPassword#";
    				String insertQuery = "INSERT INTO dir_user (id, username, firstName, lastName, password, email, active, timezone) values (?, ?, ?, ?, ?, ?, '1', '0')";
                    PreparedStatement istmt = con.prepareStatement(insertQuery);
                    istmt.setString(1, row.getProperty("UserEmail"));
                    istmt.setString(2, row.getProperty("UserEmail"));
                    istmt.setString(3, row.getProperty("UserFirstname"));
                    istmt.setString(4, row.getProperty("UserLastname"));
                    istmt.setString(5, md5(password));
    				istmt.setString(6, row.getProperty("UserEmail"));
                    istmt.executeUpdate();
    
    				//Setting role for this new user
        			String SqlSetRole = "INSERT INTO dir_user_role (roleId,userId) values ('ROLE_USER',?) ";
        			PreparedStatement statementAffectRole = con.prepareStatement(SqlSetRole);
    				statementAffectRole.setString(1, row.getProperty("UserEmail"));
        			statementAffectRole.executeUpdate();
                }
            }
        } catch (Exception ex) {
            System.err.println("Exception: " + ex.getMessage());
        } finally {
            try {
                if(con != null)
                    con.close();
            } catch(SQLException e) {}
        }
    }
    
    public static String md5Base16(String content) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(content.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                byte b = bytes[i];
                String hex = Integer.toHexString((int) 0x00FF & b);
                if (hex.length() == 1) {
                    sb.append("0");
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (Exception e) {}
        return "";
    }
    
    public static String md5(String content) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            byte[] data = content.getBytes();
            m.update(data, 0, data.length);
            BigInteger i = new BigInteger(1, m.digest());
            return String.format("%1$032X", i);
        } catch (Exception ex) {}
        return "";
    }
    
    return storeData();