Home > Enterprise >  Converting some browser JavaScript to HTML and JavaScript files - Hashing using SHA256
Converting some browser JavaScript to HTML and JavaScript files - Hashing using SHA256

Time:08-02

I used https://youtu.be/w7UrV4-G798 to help hash some passwords from a website I am creating as a personal project. It uses JavaScript in the console to hash some text but I would like to use the code below as a function in my website, as a complete JavaScript beginner I can't seem to make it work. Here is the code:

const sha256script = document.createElement('script');
sha256script.src='https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js'
document. head.appendChild(sha256script);
console.log(sha256('password')) 

I currently have the password saved like this:

<!--Password-->
<div>
  <label for="password">Password:</label>
  <input id="password" name="password" type="password" spellcheck="false" autocomplete="new-password" minlength="8" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*" required>
</div>

Thank you for the help

CodePudding user response:

This is a demo of how to set the value of the element having id as password with the hash coming from the call to sha256().

The function sha256 here is just a fake placeholder. You will replace it with your own coming from the source you specified in your questoin.

The function setPasswordValue() accepts two arguments: the css selector to specify which element to assign its value and what's the value to set.

The element to assign the value to, is selected through document.querySelector():

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

And the value of the input element is set through its value property documented here:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value

The input control's value. When specified in the HTML, this is the initial value, and from then on it can be altered or retrieved at any time using JavaScript to access the respective HTMLInputElement object's value property. The value attribute is always optional, though should be considered mandatory for checkbox, radio, and hidden.

function sha256(o){
  return "fakehash";
}

function setPasswordValue(selector, value){
  document.querySelector(selector).value = value;
}

function clickHandler(){
  setPasswordValue('#password', sha256('foo'))
}
<div>
  <label for="password">Password:</label>
  <input
    id="password"
    name="password"
    type="password"
    spellcheck="false"
    autocomplete="new-password"ù
    minlength="8"
    pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*"
    required>
</div>

<button type="button" onclick="clickHandler();">Set Password Value</button>

  • Related