Search code examples
javascriptjquerycryptojs

MD5 string not displaying correctly with html()


I have two spans with the IDs salt and password

<div>
    $salt = '<span id="salt"></span>';<br />
    $password = '<span id="password"></span>';
</div>

I then use the following jQuery code which takes the salt, adds it to the password entered by the user, and returns both a salt and hashed password (to copy into a config file)

salt = (Math.random() +1).toString(36).substr(2, 16);
$('#salt').html(salt);
hashed = CryptoJS.MD5(salt + $(this).val());
$('#password').html(hashed);

This code adds the salt to the span with the salt ID, but it doesn't add anything to the password ID.

If I enter the code alert(hashed) it will open an alert with an md5 value.

If I change .html() to .text() it works.


Solution

  • the CryptoJS.MD5() method returns an object. to convert this object to a string use it's toString() method.

    hashed = CryptoJS.MD5(value);
    var hashedString = hashed.toString();
    

    than to insert the text into an element use jQuerys text() method. the jQuery html() method is for setting an elements innerHTML value. but you want to insert unescaped text.

    $('#password').text(hashedString);
    

    if an object is passed to text() it will automatically call toString() on it, although this is not documented in the reference

    reference

    .text( text )

    The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. […] be aware that this method escapes the string provided as necessary so that it will render correctly in HTML.

    from jQuery API Documentation: text()

    .html( htmlString )

    A string of HTML to set as the content of each matched element

    from jQuery API Documentation: html()