Best way to Obfuscating JavaScript Code and Creating a Password Generator with ChatGPT

Spread the love
5/5 - (1 vote)

In this writing, we’ll learn how to make a Password Maker using HTML, CSS, and JavaScript, with the help of ChatGPT, a strong computer brain. We will also learn how to Obfuscating JavaScript Code to keep it secure from nosy folks.

Building the Password Generator

Setting Up the Environment

Before we start working on the code, let’s get our workspace ready. You’ll need a writing tool, and I suggest using Visual Studio Code (VSCode) because it has many helpful tools and add-ons.

1. Install VSCode

If you haven’t done it yet, get Visual Studio Code. Download and install it.

2. Extensions

In VSCode, install extensions for HTML, CSS, and JavaScript to enhance your coding experience.

Writing the HTML Structure

We begin by creating the HTML structure for our Password Generator. Here’s a simplified version of the HTML code:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Password Generator</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div class="container">
    <h2 class="title">Password Generator</h2>
    <div class="option">
      <label for="slider">Password Length: <span class="length-title" data-length="12">12</span></label>
      <input type="range" id="slider" min="4" max="20" value="12" step="1">
    </div>
    <div class="option">
      <input type="checkbox" id="uppercase">
      <label for="uppercase">Include Uppercase Letters</label>
    </div>
    <div class="option">
      <input type="checkbox" id="lowercase" checked>
      <label for="lowercase">Include Lowercase Letters</label>
    </div>
    <div class="option">
      <input type="checkbox" id="number" checked>
      <label for="number">Include Numbers</label>
    </div>
    <div class="option">
      <input type="checkbox" id="symbol" checked>
      <label for="symbol">Include Symbols</label>
    </div>
    <div class="option2">
      <button id="generate">Generate Password</button>
    </div>
    <div class="password-result">
      <div id="result">CLICK GENERATE</div>
      <button id="copy-btn">Copy</button>
    </div>
    <div class="info-container">
      <div class="copy-info right">Click Copy to Copy Password</div>
      <div class="copied-info left">Copied to Clipboard!</div>
    </div>
  </div>

  <script src="script.js"></script>
</body>

</html>

Styling with CSS

Next, we add CSS styles to make our Password Generator visually appealing and user-friendly. Here’s a snippet of the CSS code:

* {
    box-sizing: border-box;
  }
  
  body {
    font-family: Arial, sans-serif;
    background-color: #000000;
    color: #ffffff;
    margin: 0;
    padding: 0;
  }
  
  .container {
    max-width: 700px;
    margin: 40px auto;
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
  }
  
  .title {
    text-align: center;
  }
  
  .option {
    margin-bottom: 10px;
  }
  
  .option label {
    display: block;
  }
  
  .range-container {
    display: flex;
    align-items: center;
  }
  
  .range-container label {
    flex: 1;
  }
  
  .range-container input {
    flex: 5;
    margin-left: 10px;
  }
  
  .password-result {
    position: relative;
    margin-top: 20px;
    padding: 10px;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 5px;
  }
  
  #result {
    font-size: 24px;
    text-align: center;
    margin-bottom: 10px;
  }
  
  #copy-btn {
    position: absolute;
    top: 50%;
    right: 10px;
    transform: translateY(-50%);
    padding: 5px 10px;
    background-color: #209cff;
    color: #ffffff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.3s ease;
  }
  
  .info-container {
    display: flex;
    justify-content: space-between;
  }
  
  .copy-info,
  .copied-info {
    padding: 5px 10px;
    font-size: 14px;
    background-color: #209cff;
    color: #ffffff;
    border-radius: 5px;
    transform: translateY(200%);
    opacity: 0;
    transition: transform 0.3s ease, opacity 0.3s ease;
  }
  
  .copied-info {
    transform: translateY(0%);
  }

  #generate {
    background-color: #209cff;
    color: #ffffff;
    font-size: 18px;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    display: inline-block; /* Ensures the button is only as wide as its content */
  }
  
  .option2 {
    text-align: center;
  }
  #generate:hover {
    background-color: #0075b3;
  }
  
  @media (max-width: 500px) {
    .container {
      padding: 10px;
    }
  
    .option label {
      font-size: 14px;
    }
  
    .range-container input {
      margin-left: 5px;
    }
  
    #result {
      font-size: 18px;
    }
  
    #copy-btn {
      font-size: 12px;
      padding: 3px 6px;
    }
  
    .copy-info,
    .copied-info {
      font-size: 12px;
      padding: 3px 6px;
    }
  }
  

Implementing JavaScript Logic

Now, let’s implement the JavaScript logic for generating passwords and adding interactivity to our Password Generator. We’ll break this down into several steps:

Handling the Range Slider

We create a range slider to set the password length.

Generating Random Characters

JavaScript functions are used to generate random characters for the password, including uppercase letters, lowercase letters, numbers, and symbols.

User Interaction

We add event listeners to allow users to customize their password by selecting character types and clicking the “Generate Password” button.

Copying to Clipboard

A “Copy” button lets users easily copy the generated password to their clipboard.

Responsive Design

We make sure our Password Generator looks good on both desktop and mobile devices.

Using ChatGPT for Guidance

As we were creating our project, we asked ChatGPT for help and advice. This was especially useful when we faced problems or wanted to make our code better. ChatGPT gave us really helpful answers and suggested ways to make things even better.

JavaScript Logic

// Clear the console on every refresh
console.clear();

// Range Slider Properties.
// Fill: The trailing color that you see when you drag the slider.
// Background: Default Range Slider Background
const sliderProps = {
  fill: "#0B1EDF",
  background: "rgba(255, 255, 255, 0.214)",
};

// Selecting the Range Slider container which will affect the LENGTH property of the password.
const slider = document.querySelector(".option input[type='range']");

// Text which will show the value of the range slider.
const sliderValue = document.querySelector(".length-title");

// Using Event Listener to apply the fill and also change the value of the text.
slider.addEventListener("input", (event) => {
  sliderValue.textContent = event.target.value;
  applyFill(event.target);
});

// Selecting the range input and passing it to the applyFill function.
applyFill(slider);

// This function is responsible for creating the trailing color and setting the fill.
function applyFill(slider) {
  const percentage = ((100 * (slider.value - slider.min)) / (slider.max - slider.min)).toFixed(1);
  const bg = `linear-gradient(90deg, ${sliderProps.fill} ${percentage}%, ${sliderProps.background} ${Number(percentage) + 0.1}%)`;
  slider.style.background = bg;
  sliderValue.setAttribute("data-length", slider.value);
}

// Object of all the function names that we will use to create random letters of the password
const randomFunc = {
  lower: getRandomLower,
  upper: getRandomUpper,
  number: getRandomNumber,
  symbol: getRandomSymbol,
};

// Random more secure value
function secureMathRandom() {
  return window.crypto.getRandomValues(new Uint32Array(1))[0] / (Math.pow(2, 32) - 1);
}

// Generator Functions
// All the functions that are responsible for returning a random value that we will use to create a password.
function getRandomLower() {
  return String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}

function getRandomUpper() {
  return String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}

function getRandomNumber() {
  return String.fromCharCode(Math.floor(secureMathRandom() * 10) + 48);
}

function getRandomSymbol() {
  const symbols = "~!@#$%^&*()_+{}\":?><;.,";
  return symbols[Math.floor(Math.random() * symbols.length)];
}

// Selecting all the DOM Elements that are necessary -->

// The Viewbox where the result will be shown
const resultEl = document.getElementById("result");

// The input slider, will be used to change the length of the password
const lengthEl = document.getElementById("slider");

// Checkboxes representing the options that are responsible for creating different types of passwords based on user selection
const uppercaseEl = document.getElementById("uppercase");
const lowercaseEl = document.getElementById("lowercase");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");

// Button to generate the password
const generateBtn = document.getElementById("generate");

// Button to copy the text
const copyBtn = document.getElementById("copy-btn");

// Result viewbox container
const resultContainer = document.querySelector(".password-result");

// Text info shown after generate button is clicked
const copyInfo = document.querySelector(".copy-info.right");

// Text appear after copy button is clicked
const copiedInfo = document.querySelector(".copied-info.left");

// if this variable is true, only then the copyBtn will appear, i.e., when the user first clicks generate, the copyBtn will be interactive.
let generatedPassword = false;

// Update CSS Props of the COPY button
// Getting the bounds of the result viewbox container
let resultContainerBound = {
  left: resultContainer.getBoundingClientRect().left,
  top: resultContainer.getBoundingClientRect().top,
};

// This will update the position of the copy button based on mouse position
resultContainer.addEventListener("mousemove", (e) => {
  resultContainerBound = {
    left: resultContainer.getBoundingClientRect().left,
    top: resultContainer.getBoundingClientRect().top,
  };
  if (generatedPassword) {
    copyBtn.style.opacity = "1";
    copyBtn.style.pointerEvents = "all";
    copyBtn.style.setProperty("--x", `${e.x - resultContainerBound.left}px`);
    copyBtn.style.setProperty("--y", `${e.y - resultContainerBound.top}px`);
  } else {
    copyBtn.style.opacity = "0";
    copyBtn.style.pointerEvents = "none";
  }
});

window.addEventListener("resize", (e) => {
  resultContainerBound = {
    left: resultContainer.getBoundingClientRect().left,
    top: resultContainer.getBoundingClientRect().top,
  };
});

// Copy Password to clipboard
copyBtn.addEventListener("click", () => {
  const textarea = document.createElement("textarea");
  const password = resultEl.innerText;
  if (!password || password == "CLICK GENERATE") {
    return;
  }
  textarea.value = password;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  textarea.remove();

  copyInfo.style.transform = "translateY(200%)";
  copyInfo.style.opacity = "0";
  copiedInfo.style.transform = "translateY(0%)";
  copiedInfo.style.opacity = "0.75";
});

// When Generate is clicked, a password is generated.
generateBtn.addEventListener("click", () => {
  const length = +lengthEl.value;
  const hasLower = lowercaseEl.checked;
  const hasUpper = uppercaseEl.checked;
  const hasNumber = numberEl.checked;
  const hasSymbol = symbolEl.checked;
  generatedPassword = true;
  resultEl.innerText = generatePassword(length, hasLower, hasUpper, hasNumber, hasSymbol);
  copyInfo.style.transform = "translateY(0%)";
  copyInfo.style.opacity = "0.75";
  copiedInfo.style.transform = "translateY(200%)";
  copiedInfo.style.opacity = "0";
});

// Function responsible for generating a password and returning it.
function generatePassword(length, lower, upper, number, symbol) {
  let generatedPassword = "";
  const typesCount = lower + upper + number + symbol;
  const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter((item) => Object.values(item)[0]);

  // Doesn't have a selected type
  if (typesCount === 0) {
    return "CLICK GENERATE";
  }

  // create a loop
  for (let i = 0; i < length; i += typesCount) {
    typesArr.forEach((type) => {
      const funcName = Object.keys(type)[0];
      generatedPassword += randomFunc[funcName]();
    });
  }

  const finalPassword = generatedPassword.slice(0, length);

  return finalPassword;
}

Obfuscating JavaScript Code

After you’ve made your Password Maker, you might want to scramble your JavaScript code to keep it safe from others trying to read or figure it out easily. Here’s how you can do it using Visual Studio Code:

Install JavaScript Obfuscator

In VSCode, open the Extensions view and search for “JavaScript Obfuscator.” Install this extension.

Select Your JavaScript File

Open your JavaScript file (in this case, script.js) in VSCode.

Obfuscate the Code

Right-click anywhere in the file editor and select “Obfuscate.” This will transform your readable JavaScript code into obfuscated, hard-to-read code.

Save the Obfuscated Code

Save the obfuscated code to a new file or overwrite the existing one. Make sure to keep a backup of the original code.

Conclusion

Making a Password Maker with ChatGPT can be a fun and learning adventure. Also, when you use tools like the JavaScript Hider in Visual Studio Code, it adds an extra shield to your web projects. This makes your JavaScript code trickier for others to solve.

Remember to keep both your original and obfuscated code in a safe place, and regularly back up your projects to ensure you don’t lose any work.

Happy coding and secure password generation!

Read More

Create an Image to WebP Converter Tool with ChatGPT

Building an Image Compressor Tool using chat Gpt with HTML, CSS, and JavaScript

Scroll to Top